I have a parent class called Organism
which has a class attribute called isIntelligent
and I create a variable called fitness
based on the value of the class attribute isIntelligent
likewise:
class Organism:
isIntelligent = False
def __init__(self):
#some variables defined here
if isIntelligent:
@property
def fitness(self):
return 0
Now, I want to create two child classes, for example Rabbit
and Fox
, I want Rabbits to be intelligent and Foxs to be not. In accordance to that they should have the fitness
property.
I tried to change the value of the isIntelligent
variable inside the child classes likewise:
class Rabbit(Organism):
isIntelligent = True
class Fox(Organism):
isIntelligent = False
However, when I run the code and I expect the Rabbit objects to have the fitness
variable, but they do not.
What would be the correct way to go about this ?
CodePudding user response:
Code that isn't in a method is executed when the class is defined, so it can't be dependent on the instance. You need to put the condition inside the property method.
@property
def fitness(self):
if self.isIntelligent:
return 0
else:
return 1