Python类属性详解

python开发中,我们常常用到python的类,今天就通过实例和大家扒一扒类的属性,一起来看看吧。

 

类属性

 

1.类定义后就存在,而且不需要实例化

2.类属性使得相同类的不同实例共同持有相同变量

  

类属性实例

 

 attrb.py

  class TestCss:

    cssa = 'class-attribe'

    def __init__(self):

        self.a = 0

        self.b = 10

 

    def info(self):

        print('a:',self.a,'b:',self.b,'cssa:',TestCss.cssa)

 

    def define_a(self):

        self.c = 19

 

if __name__ == '__main__':

    # tc = TestCss()

    # tc.info()

    # tc.color = 'red'

    # print(tc.color)

    # tc = TestCss()

    # tca = TestCss()

    # tc.a = 100

    # tc.b = 200

    # tc.info()

    # tca.info()

    # tc = TestCss()

    # tc.define_a()

    # print(tc.c)

    tc = TestCss()

    tc.info()

    tca = TestCss()

    tc.info()

    TestCss.cssa = 0

    tc.info()

    tca.info()

 

程序的运行结果为:

 

 

原文链接:http://www.maiziedu.com/wiki/python/generic/

posted @ 2016-09-26 18:05  程序猿终结者  阅读(1204)  评论(0编辑  收藏  举报