python修改父类属性_如何在Python中从继承的类中设置和获取父类属性?

1586010002-jmsa.png

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 a Family instance. The Person instances would have their own copies of the familyName attribute.

You normally would code the Person constructor to take 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 to hold a reference to a Family instance:

class Person(object):

def __init__(self, personName, family):

self.personName = personName

self.family = family

where Person no longer inherits from Family. Use it like:

strauss = Family('Strauss')

johaness = Person('Johaness', strauss)

richard = Person('Richard', strauss)

print johaness.family.familyName

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值