I have the Family
and its inherited Person
classes. How do I get the familyName
attribute from the Person
class?
class Family(object):
def __init__(self, familyName):
self.familyName = familyName
class Person(Family):
def __init__(self, personName):
self.personName = personName
For instance, let these Family
and Person
objects:
strauss = Family('Strauss')
johaness = Person('Johaness')
richard = Person('Richard')
I'd like to do something such as:
print richard.familyName
and get 'Strauss'
. How can I do this?
You cannot.
Instances only inherit the parent class methods and attributes, not instance attributes. You should not confuse the two.
strauss.familyName
is an instance attribute of aFamily
instance. ThePerson
instances would have their own copies of thefamilyName
attribute.You normally would code the
Person
constructor to take two arguments:An alternative approach would be for
Person
to hold a reference to aFamily
instance:where
Person
no longer inherits fromFamily
. Use it like:In addition to Martijns suggestions, you can also create the Person from the Family instance, that way letting the family keep track of it's members:
Usage like this: