2013-04-13 72 views
8

Tôi có số Family và các lớp được thừa hưởng Person của nó. Làm cách nào để nhận thuộc tính familyName từ lớp Person?Làm thế nào để thiết lập và nhận thuộc tính lớp cha từ một lớp kế thừa trong Python?

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

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

Ví dụ, hãy để những FamilyPerson đối tượng:

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

Tôi muốn làm điều gì đó như:

print richard.familyName 

và nhận 'Strauss'. Tôi có thể làm cái này như thế nào?

Trả lời

20

Bạn không thể.

Các trường hợp chỉ kế thừa các phương thức và thuộc tính lớp cha, chứ không phải thuộc tính dụ. Bạn không nên nhầm lẫn cả hai.

strauss.familyName là thuộc tính dụ của phiên bản Family. Các trường hợp Person sẽ có riêng bản sao của thuộc tính familyName của chúng.

Bạn thường sẽ mã constructor Person để mất hai đối số:

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

johaness = Person('Johaness', 'Strauss') 
richard = Person('Richard', 'Strauss') 

Một phương pháp khác sẽ cho Person để giữ một tham chiếu đến một trường hợp Family:

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

nơi Person không còn kế thừa từ Family. Sử dụng nó như:

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

print johaness.family.familyName 
+1

Trình bày các tùy chọn tốt! –

4

Ngoài gợi ý Martijns, bạn cũng có thể tạo ra các Person từ sơ thẩm gia đình, như vậy để cho gia đình theo dõi các thành viên của nó:

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) 

Cách sử dụng như sau:

>>> 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 
Các vấn đề liên quan