Chr*_*ris 8 python attributes class
我对 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
Run Code Online (Sandbox Code Playgroud)
和
class MyClass2:
def __init__(self,p):
self.q=1
self.p=p
def AddSomething(self,x):
self.q = self.q+x
Run Code Online (Sandbox Code Playgroud)
例如的输出:
>>> my=MyClass1(2)
>>> my.p
2
>>> my.q
1
>>> my.AddSomething(7)
>>> my.q
8
Run Code Online (Sandbox Code Playgroud)
不取决于是否使用MyClass1或被MyClass2使用。inMyClass1和 inMyClass2都不会发生错误。
Sha*_*a99 11
python中的类及其实例使用类似字典的数据结构来存储信息。
因此,对于每个类定义,将分配一个字典,其中将存储类级别信息(类变量)。并且对于该特定类的每个实例,将分配一个单独的字典(self),其中将存储实例特定信息(实例变量)。
所以现在下一个问题是: 如何执行特定名称的查找??
这个问题的答案是,如果您通过某个实例访问名称,则将首先搜索特定于实例的字典,如果在那里找不到该名称,则将在类字典中搜索该名称。因此,如果在两个级别都定义了相同的值,则前一个值将被覆盖。
请注意,当您编写 d['key'] = val 其中 d 是字典时,'key' 将自动添加到字典中(如果尚未存在)。否则当前值将被覆盖。在阅读进一步的解释之前,请记住这一点。
现在让我们查看您用来描述问题的代码:
我的课堂1
class MyClass1:
q=1
def __init__(self,p):
self.p=p
def AddSomething(self,x):
self.q = self.q+x
Run Code Online (Sandbox Code Playgroud)
1. my = Myclass1(2) #create new instance and add variables to it.
MyClass = {"q" : 1}
my = {"p" : 2}
Run Code Online (Sandbox Code Playgroud)
2. my.p # =2, p will be taken from Dictionary of my-instance.
Run Code Online (Sandbox Code Playgroud)
3. my.q # =1, q will be takn from MyClass dict. (Not present in dictionary of my-instance).
Run Code Online (Sandbox Code Playgroud)
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}
Run Code Online (Sandbox Code Playgroud)
5. my.q # =8, q now is available in dictionary of my-instance.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10951 次 |
| 最近记录: |