python类属性定义_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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值