python程序设计——面向对象程序设计:方法

类中定义的方法分为四类:公有方法,私有方法,静态方法,类方法

公有方法、私有方法都属于对象,私有方法的名字以"__"开始

每个对象都有自己的公有方法和私有方法,这两类方法可以访问属于类和对象的成员

公有方法通过对象名直接调用,私有方法不能通过对象名直接调用,只能在属于对象的方法中通过self调用或在外部通过python支持的特殊方式调用

class Root:
    __total = 0
    def __init__(self,v):
        self.__value = v
        Root.__total += 1
    def show(self):
        print('self.__value:',self.__value)
        print('Root.__total:',Root.__total)
        
    @classmethod
    def classShowTotal(cls):     #类方法
        print(cls.__total)
        
    @staticmethod
    def staticShowTotal():       #静态方法
        print(Root.__total)

r = Root(3)
r.classShowTotal()  # 通过对象来调用类方法

out :
1

r.staticShowTotal()  # 通过对象来调用静态方法

out :
1

r.show()

out:
self.__value: 3
Root.__total: 1

rr = Root(5)
Root.classShowTotal()  # 通过类名调用类方法

out:
2

Root.staticShowTotal()  # 通过类名调用静态方法

out:
2

Root.show(r)   # 调用方法并访问实例成员
self.__value: 3
Root.__total: 2

猜你喜欢

转载自www.cnblogs.com/feinaio2017/p/8947165.html