0

Python知识库(1)——class variable和instance variable

Posted by nanxiao on 十二月 23, 2016 in Python知识库 |

一个好的Python实践是把创建instance variable的工作放到__init__函数中。当然可以在其它地方创建instance variable,但一定要与具体的instance相关联。举例如下:

class Base:
    def __init__(self):
        self.a = 10

    def fun1(self):
        self.b = 20

p = Base()
p.fun1()
p.c = 30

print(p.a, p.b, p.c)

运行结果:

10 20 30

参考资料:
Must all Python instance variables be declared in def init?
python class instance variables and class variables

标签:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Copyright © 2013-2017 我的站点 All rights reserved.
This site is using the Multi Child-Theme, v2.2, on top of
the Parent-Theme Desk Mess Mirrored, v2.5, from BuyNowShop.com