从具有自引用的实例内部访问类变量时会发生什么?

exh*_*uma 2 python inheritance

我的一位同事写了一个与此类似的代码:

class A(object):
    foo = "bar"


class B(A):
    def baz(self):
        print self.foo
Run Code Online (Sandbox Code Playgroud)

并且违背我的个人信仰,这很有效!我来自一个主要的Java背景,这伤害了我的眼睛......就个人而言,我会这样写:

class A(object):
    foo = "bar"


class B(A):
    def baz(self):
        print A.foo  # or dynamically determine the superclass.
Run Code Online (Sandbox Code Playgroud)

我理解,在Python中,变量名通常与"标签"进行比较.但这仍然在我的嘴里留下酸味.编写这样的代码有什么意义?这真是个坏主意吗?可能会出错吗?

我可以想象的唯一"坏"的事情是,在类层次结构的更深处,一个实例变量可能会影响类变量......所以,你可以说它是......好吗?

Jan*_*cak 5

你基本上可以做到这两点.

如果您的类只有一个父级,则可以直接使用名称引用该变量.

class A(object):
    foo = "bar"


class B(A):
    def baz(self):
        print self.foo  
Run Code Online (Sandbox Code Playgroud)

如果你使用multi,你所做的就有意义了

class A(object):
    foo = "bar"

class A2(object):
    foo = "bar 2"

class B(A, A2):
    def baz(self):
        #print foo # would throw NameError: global name 'foo' is not defined
        #print self.foo # prints "bar"
        print A.foo # prints "bar"
        print A2.foo # prints "bar 2"  
Run Code Online (Sandbox Code Playgroud)

编辑:如果我们忽略Java没有多重继承的事实,我认为它的行为方式类似.

public class A {
    String foo = "bar";
}

public class B extends A {

    public void baz() {
        System.out.println(this.foo);
    }

}
public static void main(String[] args) {
    B b = new B();
    b.baz(); // prints "bar"
}
Run Code Online (Sandbox Code Playgroud)

唯一的区别是,在Java中可以使用this.foo,super.foo但是foo,在Python中,您可以使用self.foo<superclass>.foo不使用foo