如何找到类字段的定义?

2024-06-26 09:37:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个类的构造函数中,我看到一些自变量在没有初始化的情况下被使用。例如:

def __init__(self, x):
    self.x = x + self.y

在上面的示例中,您可以看到,self.y在没有初始化的情况下被使用。我的假设是这个字段的值来自于超类。你知道吗

悬停,在超类中我也看不到self.y的定义。那么,它从哪里来?你知道吗

添加了

我需要补充的是,这个字段也没有定义为“类属性”。所以,我有这样的东西:

class MyClass(SomeBaseClass):
    def __init__(self, x, y):
        self.aaa = self.bbb + self.ccc
        # some other code

增加了2个

我做了以下检查:

class MyClass(SomeBaseClass):
    def __init__(self, x, y):
        print(self.__dict__) # <--- please notice this line !!!!!!!!!
        self.aaa = self.bbb + self.ccc
        # some other code

因此,我看到了一个包含键和值的字典。所以,我的假设是这些值来自基类。但是,如果我转到基类,并向构造函数添加prints

def __init__(self, x, y, z):
    print('some additional print in the beginning')
    # some code here
    print('print at the end of the constructor')

然后我看不到这些打印(就好像基类的构造函数没有被执行一样)。你知道吗


Tags: theself定义initdefmyclass情况code
3条回答

如果重写init,则不会执行基类的init方法。必须在init中显式调用super()。init()。如果您想找出哪些类用于查找实例属性,请执行:MyClass.mro()。据我所知,__getattribute__从左到右搜索您将得到的列表。你知道吗

如果self.y没有在__init__之前赋值,那么这只能是class-attribute(可能是继承的)。self通常表示类的实例,但是instance-attributes首先在init()中初始化。如果它不在那里,在这一点上它就不是instance-attribute。你知道吗

示例:

class test :
    y = 7  # scope: class
    def __init__( self ):
        self.x = self.y + 1  # scope: instance

a = test()
a.x  # 8   # scope: instance
a.y  # 7   # scope: instance, pulled from class
test.y # 7   # scope: class 

对于你的研究:In Python, it’s all about the attributes
关于类和实例属性之间差异的最佳解释,我到目前为止发现的

类的构造函数中有一些self.*属性,它们可以来自父类(超类)或子类。你知道吗

如果super().__init__()不是从所考虑的类的构造函数调用的,那么在父类的构造函数中完成的定义还没有实现。因此,属性不能来自父类。你知道吗

也可能发生的情况是,某个子类在其构造函数中创建了一些定义(例如,引入了一些属性),然后调用其父类的构造函数(这意味着调用了类的构造函数)。在这种情况下,您的类将看到在子类中定义的属性。它们将被视为自身的属性。你知道吗

例如:

class your_class():

    def __init__(self):
        print self.x # How can we print self.x if it does not exist?

class child_class():

    def __init__(self, x):
        self.x = x
        super().__init__() # here is constructor of the parent class (your_class) is called and this constructor will see self.x defined here.

相关问题 更多 >