如何在Python中从继承的类中设置和获取父类属性? [英] How to set and get a parent class attribute from an inherited class in Python?

查看:1025
本文介绍了如何在Python中从继承的类中设置和获取父类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有家庭及其继承的 Person 课程。如何从 Person 类中获取 familyName 属性?

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

例如,让这些 Family Person 对象:

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

我想做一些事情,例如:

I'd like to do something such as:

print richard.familyName

并获取 Strauss'。如何做到这一点?

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

推荐答案

不能。

只继承父类的方法和属性,而不是 instance 属性。

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

strauss.familyName 是一个实例属性a Family 实例。 Person 实例将拥有 familyName 属性的自己的副本。

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

您通常会将 Person 构造函数编码为两个参数:

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

另一种方法是 Person 保存对 Family instance:

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

其中 Person 不再继承自 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

这篇关于如何在Python中从继承的类中设置和获取父类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆