类属性:
class Toy(object):
count = 0
def __init__(self,name):
self.name=name
Toy.count +=1
@classmethod
def toy_count(cls):
print('玩具的数量 %d' %(cls.count))
toy1 = Toy('乐高')
toy2 = Toy('泰迪熊')
Toy.toy_count()
结果:
玩具的数量 2
静态调用:
class Cat(object):
@staticmethod
def call():
print('喵喵')
Cat.call() #不需要创建对象可以直接调用方法(类名。方法名)
结果:
喵喵
变量私有化
class Student(object):
def __init__(self,name,score):
self.__name =name #变量前面加上两个下划线表示对变量进行私有化,不能随意访问和更改
self.__score =score
def get_grand(self): #私有化后可以在类中设定方法,通过方法去调用
print('name is %s ,grand is %d ' %(self.__name,self.__score))
def get_name(self):
print(self.__name)
def get_score(self):
print(self.__score)
tom = Student('tom',90)
#print(tom.name) #私有变量无法查看,会报错
#print(tom.score)
tom.get_name() #通过方法调用查看
tom.get_score()
结果:
tom
90