How to set and get the attribute of a parent class from an inherited class in Python?

I have Family and its inherited Person classes. How to get familyName attribute from Person class?

 class Family(object): def __init__(self, familyName): self.familyName = familyName class Person(Family): def __init__(self, personName): self.personName = personName 

For example, let these Family and Person objects:

 strauss = Family('Strauss') johaness = Person('Johaness') richard = Person('Richard') 

I would like to do something like:

 print richard.familyName 

and get 'Strauss' . How can i do this?

+8
python inheritance class
source share
2 answers

You can not.

Instances only inherit the methods and attributes of the parent class, not the attributes of the instance. You should not confuse them.

strauss.familyName is an attribute of an instance of a Family instance. Person instances will have their own copies of the familyName attribute.

You usually code the Person constructor to accept two arguments:

 class Person(Family): def __init__(self, personName, familyName): super(Person, self).__init__(familyName) self.personName = personName johaness = Person('Johaness', 'Strauss') richard = Person('Richard', 'Strauss') 

An alternative approach would be for Person reference the Family instance:

 class Person(object): def __init__(self, personName, family): self.personName = personName self.family = family 

where Person no longer inherited from Family . Use it as:

 strauss = Family('Strauss') johaness = Person('Johaness', strauss) richard = Person('Richard', strauss) print johaness.family.familyName 
+20
source share

In addition to Martijns suggestions, you can also create an instance of Person from the Family, thereby allowing the family to track its members:

 class Person(object): def __init__(self, person_name, family): self.person_name = person_name self.family = family def __str__(self): return ' '.join((self.person_name, self.family.family_name)) class Family(object): def __init__(self, family_name): self.family_name = family_name self.members = [] def add_person(self, person_name): person = Person(person_name, self) self.members.append(person) return person def __str__(self): return 'The %s family: ' % self.family_name + ', '.join(str(x) for x in self.members) 

Using:

 >>> strauss = Family('Strauss') >>> johannes = strauss.add_person('Johannes') >>> richard = strauss.add_person('Richard') >>> >>> print johannes Johannes Strauss >>> print richard Richard Strauss >>> print strauss The Strauss family: Johannes Strauss, Richard Strauss 
+4
source share

All Articles