Reputation: 143
I want to use a dictionary in a class (Animals) and want an another class (breeding) to refer to this class. (Animals reads the dictionary and creates an another dictionary with the keys of the first one and the values of 0, 'feed' grows 'strength' with the value of 'food' and the 'breeding' class would make 'children' with the amount of 'strength'.)
The code in the Animals class works, but it does not pass the names (keys) of the dictionary to the breeding class:
" 'breeding' object has no attribute 'strength' "
Does anybody have a suggestion how to solve this?
class Animals:
def __init__(self, dictionary):
self.dictionary=dictionary
self.strength={}
for name, value in dictionary.items():
self.strength[name]=0
setattr(self, name, value)
print("Name: {} ".format(name))
def feed(self, name, food):
self.food=food
self.strength[name]+= food
print(self.strength[name])
def read(self):
for name in self.my_dict:
print("Name: {} Strength: {}".format(name,self.strength[name]))
class breeding(Animals):
def __init__(self, name,child=0):
self.child=child
if self.strength[name] >= 10:
child += (self.strength[name]/10)
self.my_dict[name] = (self.strength[name]%10)
print("Strength level: {}, number of children: {}".format(self.strength[name], child))
else:
print("Strength level only {}, no new children".format(self.strength[name]))
Upvotes: 0
Views: 1219
Reputation: 15891
When you inherit from a class (like in this case breeding
inherits from Animals
) you need to invoke __init__
of the parent class in child class, otherwise it is not executed and all initialization that should happen there does not happen.
That's why you get the error message - because Animal
"part" of breeding
was not initialized correctly.
__init__
in Animals
gets dictionary
and that means that breeding.__init__
should pass dictionary
when calling Animals.__init__
.
Do it like this:
class breeding(Animals):
def __init__(self, name, child=0):
dictionary = ... # create dictionary that should be passed to parent
super(breeding, self).__init__(dictionary) # invoke Animal's __init__
# do other initialization of the `breeding` itself
...
Upvotes: 1