类方法和静态方法

类方法

class Person(object):
    # 类属性 可以私有
    __country = "中国"

    # 类方法 修饰器
    # 类方法也有一个形参 是cls 就是这个类
    # 获取私有的类属性
    @classmethod
    def get_country(cls):
        return cls.__country

    # 给私有的类属性赋值
    @classmethod
    def set_counry(cls, new_country):
        cls.__country = new_country

# print(Person.country)
# 获取私有类属性了
# 调用类方法的方式
# 01: 类名.类方法名()
# print(Person.get_country())
# 02: 对象名.类方法名()
# p = Person()
# print(p.get_country())

#
Person.set_counry("美国")
print(Person.get_country())

静态方法

# 格式:def 方法名(self):
# 一 实例方法 调用
# 01格式: 对象名.实例方法名()
# p = Person()
# print(p.get_name())
# 02格式: 不建议写
# Person.get_name(Person())

# 格式:@classmethod
#      def 方法名(cls)
# 二 类方法 调用
# 01格式: 类名.类方法名()
# print(Person.get_country())
# 02格式: 对象名.类方法名()
# p = Person()
# print(p.get_country())

# 格式:@staticmethod
#      def 方法名():
# 三 静态方法 调用
# 01格式: 类名.静态方法名()
# Person.hello_python()
# 02格式: 对象名.静态方法名()
# p = Person()
# p.hello_python()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值