首页 / PYTHON / Python类属性及其初始化
Python类属性及其初始化
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python类属性及其初始化,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2111字,纯文字阅读大概需要4分钟。
内容图文
![Python类属性及其初始化](/upload/InfoBanner/zyjiaocheng/692/b08fa2e0a063460a839dca2ac82bc634.jpg)
我是python的新手,最近这些天我在探索课程.我有一个关于类内部的属性和变量的问题:仅通过类主体中的q = 1定义属性和通过__init__内部的self.q = 1定义属性之间有什么区别?例如,以下两种可能性之间有什么区别?
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.
内容总结
以上是互联网集市为您收集整理的Python类属性及其初始化全部内容,希望文章能够帮你解决Python类属性及其初始化所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。