当前位置: Python基础教程 > 08-面向对象b > 阅读正文

python的类属性, 类方法, 静态方法

2021.6.21.   381 次   759字

在python面向对象中, 有2种属性

  • 类属性
  • 对象属性

类属性, 指的是属于此类的多个对象共享这些变量

此外, 有3种方法

  • 对象方法
  • 类方法
  • 静态方法

类方法也是指属于此类的所有对象共享使用, 静态方法和类方法有少量区别

class Tool(object):

    count = 0   #类属性

    def __init__(self, name=""):
        Tool.count += 1

    @classmethod   #此注解表示类方法
    def sub_count(cls):

        cls.show_help()  #访问静态方法
        cls.count -= 1   #访问类属性
        cls.show_test()  #访问类方法

    @classmethod
    def sub_test(cls):
        print("另一个类方法")


    @staticmethod   #此注解表示静态方法
    def show_help():
        Tool.show_test()    #访问静态方法
        # cls.sub_count()    #无法访问类方法
        print("一个静态方法")

    @staticmethod
    def show_test():
        print("另一个静态方法")


tool1 = Tool()
tool2 = Tool()
tool3 = Tool()

print(tool1.count)  #若无同名对象属性, 将输出类属性
print(Tool.count)  #输出的是类属性

Tool.sub_count()   #调用类方法, 不能访问对象属性方法, 能访问类属性, 能访问静态方法

Tool.show_help()  #调用静态方法, 它不能访问对象属性, 也不能访问类属性

无论是类方法, 还是静态方法, 均使用使用以下方式获取属性, 设置值仅能用后者

  • 对象名.方法名() ——– 仅限无对象方法重名,
  • 类名.方法名() ——– 推荐使用

静态方法, 会优先于类方法加载, 你可以在类方法中调用静态方法, 反过来却不行

本篇完,还有疑问?

加入QQ交流群:11500065636 IT 技术交流群