python类的属性_Python类属性及其初始化

本文讨论了Python类中实例属性与类属性的区别。类属性通过在类定义中直接赋值,如`q=1`,与实例无关,可通过类本身访问。而实例属性在`__init__`方法中通过`self.q=1`创建,与特定实例相关。实例属性可以通过实例或类访问,但修改时会改变实例的属性,而非类属性。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

I'm quite new in python and during these days I'm exploring classes. I have a question concerning attributes and variables inside classes: What is the difference between defining an attribute via just q=1 in the body of the class and via defining self.q=1 inside the __init__? For example, what is the difference between the following two possibilities?

class MyClass1:

q=1

def __init__(self,p):

self.p=p

def AddSomething(self,x):

self.q = self.q+x

and

class MyClass2:

def __init__(self,p):

self.q=1

self.p=p

def AddSomething(self,x):

self.q = self.q+x

The output of for example:

>>> my=MyClass1(2)

>>> my.p

2

>>> my.q

1

>>> my.AddSomething(7)

>>> my.q

8

does not depend on whether MyClass1 or MyClass2 is used. Neither in MyClass1 nor in MyClass2 does an error occur.

解决方案

q=1 inside the class is a class attribute, associated with the class as a whole and not any particular instance of the class. It is most clearly accessed using the class itself: MyClass1.q.

A instance attribute is assigned directly to an instance of a class, usually in __init__ by assigning to self (such as with self.p = p), but you can assign attributes to an instance at any time.

Class attributes can be read either using the class binding (MyClass.q) or an instance binding (my.q, assuming it is not shadowed by an instance attribute with the same name). They can only be set, however, using a class binding. Setting a value with an instance binding always modifies an instance attribute, creating it if necessary. Consider this example:

>>> a = MyClass1()

>>> a.q

1

>>> a.q = 3 # Create an instance attribute that shadows the class attribute

3

>>> MyClass1.q

1

>>> b = MyClass1()

>>> b.q # b doesn't have an instance attribute q, so access the class's

1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值