Python类属性及其初始化
问题内容:
我是python的新手,最近这些天我在探索课程。我有一个关于类内部的属性和变量的问题:通过仅q=1
在类的主体中定义属性和通过self.q=1
在内部定义属性有什么区别__init__
?例如,以下两种可能性之间有什么区别?
class MyClass1:
q=1
def __init__(self,p):
self.p=p
def AddSomething(self,x):
self.q = self.q+x
和
class MyClass2:
def __init__(self,p):
self.q=1
self.p=p
def AddSomething(self,x):
self.q = self.q+x
输出例如:
>>> my=MyClass1(2)
>>> my.p
2
>>> my.q
1
>>> my.AddSomething(7)
>>> my.q
8
不依赖于是否MyClass1
或MyClass2
使用。进入MyClass1
或进入MyClass2
都不会发生错误。
问题答案:
python中的类及其实例使用类似字典的数据结构来存储信息。
因此,对于每个类定义,将分配一个字典,用于存储类级别信息(类变量)。并且对于该特定类的每个实例,将分配一个单独的字典(自身),该实例将在其中存储实例特定信息(实例变量)。
现在,下一个问题是: 如何执行对特定名称的查找?
这个问题的答案是,如果您通过某个实例访问名称,则将首先搜索实例特定的词典,如果在该实例中找不到名称,则将在类词典中搜索该名称。因此,如果在两个级别上定义了相同的值,则将覆盖前一个值。
请注意,当您编写d [‘key’] = val时,其中d是字典,如果’key’不存在,它将自动添加到字典中。
否则,当前值将被覆盖。在阅读进一步的说明之前,请记住这一点。
现在,让我们看一下您用来描述问题的代码:
MyClass1
class MyClass1:
q=1
def __init__(self,p):
self.p=p
def AddSomething(self,x):
self.q = self.q+x
1. my = Myclass1(2) #create new instance and add variables to it.
MyClass = {"q" : 1}
my = {"p" : 2}
2. my.p # =2, p will be taken from Dictionary of my-instance.
3. my.q # =1, q will be takn from MyClass dict. (Not present in dictionary of my-instance).
4. my.AddSomething(7) # This method access the value of q (using self.q) first
# which is not defined in my dict and hence will be taken
# from dictionary of MyClass. After the addition operation,
# the sum is being stored in self.q. Note that now we are
# adding the name q to Dictionary of my-instance and hence
# a new memory space will be created in Dictionary of my-instance
# and the future references to self.q will fetch the value
# of self.q from dictionary of my-instance.
MyClass = {"q" : 1}
my = {"p" : 2, "q" : 8}
5. my.q # =8, q now is available in dictionary of my-instance.