Python入门到精通

Python基础019--静态方法、类方法和类属性

2018-02-28  本文已影响4人  不一样的丶我们

静态方法、类方法和类属性

In [43]: class Test(object):
    ...:     def instancefun(self):                     # 实例方法
    ...:         print('instancefun')
    ...:         print(self)
    ...:     @classmethod
    ...:     def classfun(cls):                         # 类方法
    ...:         print('classfun')
    ...:         print(cls)
    ...:     @staticmethod
    ...:     def staticfun():                           # 静态方法
    ...:         print('staticfun')
    ...:     def function():                            # 普通函数
    ...:         print('func')
    ...:         
    In [44]: t = Test()                                 # 实例化一个的对象
    In [45]: t.instancefun()
    instancefun
    <__main__.Test object at 0x7f99fc879510>
    In [46]: Test.classfun()                            # 类调用类方法
    classfun
    <class '__main__.Test'>
    In [47]: t.classfun()                               # 对象调用类方法
    classfun
    <class '__main__.Test'>
    In [48]: Test.staticfun()                           # 类调用静态方法
    staticfun
    In [49]: t.staticfun()                              # 对象调用静态方法                          
    staticfun
    In [50]: Test.instancefun(t)                        # 类调用实例方法需要传递参数
    instancefun
    <__main__.Test object at 0x7f99fc879510>
    
# 类属性
In [55]: class Person(object):
    ...:     num = 100 
    ...:     def __init__(self):
    ...:         self.name = "zzz"
    ...:     def func(self):
    ...:         self.age = 100
    ...:         

In [56]: p1 = Person()
In [57]: p1.name = "aaa"                        # 通过实例化对象修改属性,发现属性并没有修改
In [58]: p2 = Person()
In [59]: print(p1.name)
aaa
In [60]: print(p2.name)
zzz
In [61]: Person.num = 200                       # 通过类对象修改属性,发现属性修改了
In [62]: print(p1.num)
200
In [63]: print(p2.num)
200

In [85]: class Test:
    ...:     __name = 'aaa'
    ...:     def a(self):
    ...:         print Test.__name
    ...:         

In [86]: a = Test()
In [87]: a.a()
aaa
In [88]: print Test.__name                          # 不能直接访问私有属性
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-88-56cfd6a10fe4> in <module>()
----> 1 print Test.__name

AttributeError: class Test has no attribute '__name'

In [89]: print a._Test__name                        # 通过实例对象进行访问/也可以通过类对象进行访问
aaa
上一篇 下一篇

猜你喜欢

热点阅读