gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:23:32 25 4
gpt4 key购买 nike

我的一个同事写了一个类似这样的代码:

class A(object):
foo = "bar"


class B(A):
def baz(self):
print self.foo

与我个人的信念相反,这奏效了!我主要来自 Java 背景,这伤害了我的眼睛......就个人而言,我会这样写:

class A(object):
foo = "bar"


class B(A):
def baz(self):
print A.foo # or dynamically determine the superclass.

我知道,在 Python 中,变量名经常被比作“标签”。但这仍然在我嘴里留下酸味。像这样编写代码意味着什么?这真的是个坏主意吗?会不会出什么问题?

我能想到的唯一“坏”是在类层次结构的更深处,一个实例变量可能会遮蔽类变量……所以,你可以说它……好吧?

最佳答案

基本上两者都可以。

如果你的类只有一个父类,你可以直接用名称引用变量。

class A(object):
foo = "bar"


class B(A):
def baz(self):
print self.foo

如果你使用 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"

编辑:如果我们忽略 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"
}

唯一的区别是在 Java 中它可以通过 this.foo 访问, super.foo还有foo ,而在 Python 中你可以只使用 self.foo<superclass>.foo , 但不是 foo

关于python - 当您从具有自引用的实例内部访问类变量时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20298881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com