Python类属性及其初始化

Python类属性及其初始化,第1张

Python类属性及其初始化

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.


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5508195.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存