面向对象--类中的绑定方法和非绑定方法

一:绑定方法

1.绑定到对象的方法:没有被任何装饰器装饰的方法。

在类中定义的函数默认都是绑定到对象的方法

特点:参数的第一个必须是self 表示当前对象本身,使用对象来调用,调用时会自动传入对象

2.绑定到类的方法:用 classmethod 装饰器装饰的方法。

特点:参数的第一个必须是cls表示当前类本身,使用类名来调用,调用时会自动传入类

二:非绑定方法:用staticmethod装饰器装饰的方法

特点:不与类或对象绑定,类和对象都可以调用,但是没有自动传值那么一说。就是一个普通函数

不过由于作用域在类中所以需要使用类或对象类调用

 

总结

绑定到类的方法与绑定到对象的方法总结

异同点:

  相同:

  绑定对象调用时都有自动传参的效果

  绑定到谁给谁就由谁来调用

  不同:

  绑定到类的方法自动传入当前类

  绑定到对象的方法自动传入当前对象

 

案例

class Student:
    school = "Tsinghua" 
    
    def say_hello(self):# 绑定到对象的方法
        print(self)
        print("hello i am a student my name is %s" % self.name)
    
    def __init__ (self,name): #绑定到对象的方法
        self.name = name
        
    @classmethod     # 绑定到类的方法
    def school_info(cls):
        print(cls)
        print("the student from %s" % cls.school)
    
        
stu1 = Student("Jack")
print(stu1)
#输出 <__main__.Student object at 0x1063112e8>

#1.调用对象绑定方法
stu1.say_hello()
#输出 <__main__.Student object at 0x1063112e8>
#输出 hello i am a student my name is Jack

#查看对象绑定方法
print(stu1.say_hello)
#输出 <bound method Student.say_hello of <__main__.Student object at 0x10552b2e8>>
#含义 这个绑定方法是Student类中的say_hello函数,绑定到地址为0x10552b2e8的Student对象

#绑定方法本质上也是函数 只要能找到它就能调用它所以你可以这样来调用它 
Student.say_hello(stu1)
#输出 <__main__.Student object at 0x103818390>
#输出 hello i am a student my name is Jack

print(Student)
#输出 <class '__main__.Student'>
#2.调用类绑定方法 Student.school_info() #输出 <class '__main__.Student'> #输出 the student from Tsinghua #查看类绑定方法 print(Student.school_info) #输出 <bound method Student.school_info of <class '__main__.Student'>> #含义 这个绑定方法是Student类中的school_info函数,绑定到Student这个类

  

原文地址:https://www.cnblogs.com/wakee/p/10834795.html