python - 继承:获取__init__的属性

标签 python inheritance

在下面的示例中,B 类或 C 是否可以访问 A 中的 a 属性 内部类?

class A:

    def __init__(self, a):
        self.a = a

    def C_test(self):
        for i in range(4):
            c = self.C()

class C:
    print(self.a)


class B(A):

    def __init__(self):
        print(self.a)

我怎么会收到这个错误?

Traceback (most recent call last):
  File "/Users/home/Desktop/Pygame/test.py", line 1, in <module>
    class A:
  File "/Users/home/Desktop/Pygame/test.py", line 10, in A
    class C:
  File "/Users/home/Desktop/Pygame/test.py", line 11, in C
    print(self.a)
NameError: name 'self' is not defined

最佳答案

self 不是 Python 中的特殊变量名称 - 它只是通常为方法的第一个参数指定的名称,该名称绑定(bind)到调用该方法的对象。

类 C 中的 self.a 不会出现在 self 被列为参数的方法定义中,因此 self 在那里没有任何意义。

关于python - 继承:获取__init__的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22163232/

相关文章:

python - 为什么我的某些文件在安装使用 setuptools 打包的 python 模块时不可用?

python 正则表达式不检测方括号

java - 在 Serializable 类中使用私有(private)构造函数扩展类

Python3 : inheriting from list breaks automagically provided __ne__ when __eq__ is defined?

python - Bokeh:确定哪个模型调用了 on_change 事件处理程序

python - 为什么 list.append(x) 比 list += l[x] 更高效?

css - 上下文相关的 CSS 样式

c++ - 私有(private)继承

c++ - 设置一系列基类/派生类来处理天气数据

Python - 对每一行使用 rsplit 将字符串转换为表格