面向对象-对象方法/静态方法/类方法

对象方法/静态方法/类方法

1、对象方法

  • 定义

    定义在类中

  • 调用方式

    通过对象进行调用

  • 调用格式

    对象.方法名([参数])

  • 特性

    在对象内部以引用的方式 使用类的属性和方法

  • self

    self为当前调用它的那个对象 也就是说 谁调用的它 则self就是谁

2、静态方法

  • 定义

    定义在类中

  • 格式

    @staticmethod

  • 调用方式

    使用类名/对象进行调用

  • 调用格式

    类名/对象.方法名([参数列表])

  • 特性

    无论使用类、还是对象去调用 都无法获取内部的属性和方法 完全独立的一个方法

  • 实例

    class Test:
        def say(self):
            print('普通的对象方法')
    
        @staticmethod
        def speak(*args, **kwargs):
            print(args, kwargs)
            print('静态方法@staticmethod')
    
    t = Test()
    # t.speak()
    Test.speak(1,2,3, name='lucky')
    

3、类方法

  • 定义

    定义在类中

  • 定义格式

    @classmethod

  • 调用方式

    类名/对象.方法名(建议使用类)

  • 调用格式

    类名.方法名([参数列表])

  • 特性

    在类方法内部可以引用类的属性和方法

  • 注意

    定义函数的第一个参数 必须为cls 其余参数按顺序摆放即可 调用类方法的时候 忽略第一个参数cls

  • cls

    代表当前类名

  • 实例

    class Test:
        name = 'lucky'
    
        @classmethod
        def test(cls):
            print(cls)
            return cls()
    t = Test()
    # Test.test()
    # t.test()
    # print(Test)
    print(Test.test().name)
    

4、动态添加类方法

  • 概述

    添加类方法 就是将这个方法添加给类 因此 添加类方法的时候使用的是类, 而不是对象

  • 将方法直接赋值给类

  • 实例

    class Test:
        pass
    
    @classmethod
    def run(cls):
        print('大伟 is running...')
    
    Test.run = run
    Test.run()
    

5、动态添加静态方法

  • 概述

    添加静态方法 就是将这个方法添加给类 所以直接给类去添加的

    使用@staticmethod

  • 实例

    class Test:
        pass
    
    @staticmethod
    def test():
        print('静态方法')
    
    Test.test = test
    Test.test()
    
posted @ 2022-03-18 14:15  寻月隐君  阅读(97)  评论(0编辑  收藏  举报