python - 对派生类中的 self 以及与基类成员变量的关系感到困惑

标签 python class

在下面的代码示例中,我在派生类 b 中使用 self.number,并且 number 在 a(基类)中定义。如果在基类中以这种方式定义数据成员,它是否总是可以被任何派生类访问?

我正在使用Python 2.7。这是引用基对象成员变量的正确方法吗?

class a(object):
    def __init__(self, number):
        self.number = number
        print "a __init__ called with number=", number

    def printme(self):
        print self.number



class b(a):
    def __init__(self, fruit):
        super(b, self).__init__(1)
        self.fruit = fruit
        print "b __init__ called with fruit=", fruit

    def printme(self):
        print self.number


cl1 = a(1)
cl1.printme()

cl2 = b("apple")
cl2.printme()

最佳答案

除非您在子类中执行某些操作来消除它,否则是的。分配给 Python 对象的属性只是添加到对象的 __dict__ 中。 (除了使用槽或覆盖 __setattr__ 来执行非标准操作的相对罕见的情况),并且绑定(bind)成员方法的隐式第一个参数对于源自子级或父级的方法将是相同的类(class)。普通实例属性(尽管不是方法或类属性)不以任何方式绑定(bind)到特定的类定义,仅绑定(bind)到它们所属的对象实例。

该声明的一个警告是名称以双下划线开头的属性。它们仍将添加到 __dict__并且可访问,但它们将被名称损坏,因此如果使用属性名称的损坏转换进行检索,则只能在定义类外部访问。

关于python - 对派生类中的 self 以及与基类成员变量的关系感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17701383/

相关文章:

java - 使用通配符导入类

javascript - 如何在 Google Closure 中使用 var_args 调用父类的构造函数?

ruby - 您是否曾在任何 Ruby 代码中使用过 "class instance variable"?

python - 根据 Pandas 中的行号获取多索引值

python - 如何获得 GTK 中的默认颜色?

python - 如何获取 Django 中超过一天的所有对象?

c++ - '{' token 错误之前的预期类名

c# - 在 c# 中使用 python webservice 时遇到问题

python - 如何为我的数据创建条形图?

c# - 字符串到方法类