Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 混淆派生类中的self和基类成员变量的关系_Python_Class - Fatal编程技术网

Python 混淆派生类中的self和基类成员变量的关系

Python 混淆派生类中的self和基类成员变量的关系,python,class,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

在下面的代码示例中,我在派生类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对象的属性只是添加到对象的
\uuuuu dict\uuuuu
(除了使用插槽或覆盖
\uuuuuuuu setattr\uuuuu
以执行非标准操作的相对少见的情况),对于源自子类或父类的方法,绑定成员方法的隐式第一个参数将是相同的。普通实例属性(虽然不是方法或类属性)不以任何方式绑定到特定的类定义,只绑定到它们所属的对象实例


该语句的一个警告是名称以双下划线开头的属性。它们仍然会被添加到
\uuu dict\uuuu
中并可访问,但它们的名称会被破坏,因此只有在使用属性名称的破坏转换检索时才能在定义类之外访问。

方法也是如此,因此在
类b
中重新定义
printme()
是多余的,正如目前所写的那样,@PaulGriffiths方法与它们的定义类相关联,而不是与调用它们的实例相关联,但在本例中,它们的功能类似。