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

前端 未结 2 1310
耶瑟儿~
耶瑟儿~ 2020-12-08 20:15

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

2条回答
  •  粉色の甜心
    2020-12-08 20:56

    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:

    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)
    

    Usage like this:

    >>> 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
    

提交回复
热议问题