绑定给类的方法,对象来调用;与绑定给对象的方法,类来调用的区别

绑定给类的方法,类来调用,对象可以调用吗?

# 首先创建一个类,和绑定给类的方法index
class MyClass:  
    @classmethod  
    def index(cls):  
        print("hello index")  

  

实例化对象:

obj = MyClass()

  

使用对象调用绑定给类的方法:

obj.index()

# 返回hello index

  

结论:可以

 

绑定给对象的方法,对象来调用,类可以调用吗?

# 创建一个类,方法默认为绑定给对象的方法
class MyClass:  
    
    def index(self):  
        print("hello index")  

  

# MyClass.index() 无法直接调用

# 需要传入对象
obj = MyClass()

# 传入对象才能调用
MyClass.index(obj)   

# 返回hello index

  

如果是静态对象?

class MyClass:  
    @staticmethod
    def index(self):  
        print("hello index")  

  

使用类直接调用:

MyClass.index()

# 返回 hello index

  

结论

无法直接调用,需要传入对象才能调用
想要调用,必须要为静态对象
posted @ 2023-11-29 17:23  wellplayed  阅读(18)  评论(0编辑  收藏  举报