栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python类属性及其初始化

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/516976.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号