python ——类属性,静态调用,变量私有化

类属性

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值