I am trying to create a class that has the base and height of a triangle and returns the area.
However when I try to print it tells me:
Unresolved reference 'base'
Unresolved reference 'altura'
What am I doing wrong?
class Rectangulo:
base ='4'
altura='2'
def Resultado(self,base,altura):
area=((base*altura)/2)
return f'{area}'
mi_cadena = Rectangulo()
print(mi_cadena.Resultado())
The variables
base
andaltura
, as they are definedthey are class variables , not instance variables .
Class variables are associated with the class as a whole, not with a particular object (an instance of the class). To use them you have to put the name of the class before them, as in this test function:
The function
Resultado
hasbase
andaltura
for parameters, which although they are called the same, have no relation to the class variablesbase
andaltura
. Also, they are required parameters, and you have to provide them when calling the function.Corrected version
Test:
produces:
correct form
The class
Rectangulo
is poorly modeled. A rectangle is defined by its base and height, and each instance should receive both parameters in the method__init__
, while the functionarea
returns the area of that rectangle:Proof:
produces: