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

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

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

  

实例化对象:

1
obj = MyClass()

  

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

1
2
3
obj.index()
 
# 返回hello index

  

结论:可以

 

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

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

  

1
2
3
4
5
6
7
8
9
# MyClass.index() 无法直接调用
 
# 需要传入对象
obj = MyClass()
 
# 传入对象才能调用
MyClass.index(obj)  
 
# 返回hello index

  

如果是静态对象?

1
2
3
4
class MyClass: 
    @staticmethod
    def index(self): 
        print("hello index"

  

使用类直接调用:

1
2
3
MyClass.index()
 
# 返回 hello index

  

结论

无法直接调用,需要传入对象才能调用
想要调用,必须要为静态对象
posted @   wellplayed  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示