1.1、绑定方法
绑定方法分为绑定到对象的方法,和绑定到类的方法。绑定方法指的是类中定义的方法绑定给谁,谁调用,调用的时候自身作为第一个参数自动传值。
绑定到对象的方法
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def learn(self):
print('%s is learning')
print(Student.learn)
# <function Student.learn at 0x00000149B5398B70>
s1 = Student('小明', 18)
print(s1.learn)
# <bound method Student.learn of <__main__.Student object at 0x00000149B52F3E10>>
类中定义的方法不加修饰的话都是给对象用的,对象在使用时直接调用,并把自身当作第一个参数传入。
绑定到类的方法 classmethod
classmethod绑定到类,类在使用时会将类本身当做参数传给类方法的第一个参数,对象来调用也会将类当作第一个参数传入
class Student:
name = '北大'
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def learn(cls):
print('%s is learning'%self.name)
s1 = Student('小明', 18)
print(Student.learn)
# <bound method Student.learn of <class '__main__.Student'>>
Student.learn()
# 北大 is learning
# s1.learn()
# 北大 is learning
1.2、非绑定方法 staticmethod
非绑定方法staticmethod装饰,不与类和对象绑定,就是一个普通工具,
class Student:
name = '北大'
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def learn(x):
print('%s is learning'%x.name)
Student.learn(Student)
s1 = Student('小明', 18)
s1.learn(s1)
北大 is learning
小明 is learning
class Student:
def __init__(self, name, age):
self.host = name
self.port = age
self.id = self.create_id()
@staticmethod
def create_id():
m = hashlib.md5(str(time.time()).encode('utf-8'))
return m.hexdigest()
s1 = Student('小明', 18)
print(s1.__dict__)
# {'host': '小明', 'port': 18, 'id': '68eb283957093535025e8f4d85660316'}
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
self.id = self.create_id()
@staticmethod
def create_id():
m = hashlib.md5(str(time.time()).encode('utf-8'))
return m.hexdigest()
@classmethod
def m1(cls):
return cls('小红', 19)
s1 = Student('小明', 18)
s2 = Student.m1()
print(s1.__dict__)
# {'name': '小明', 'age': 18, 'id': 'ab5564ad93932badc2391034f61eafa4'}
print(s2.__dict__)
# {'name': '小红', 'age': 19, 'id': 'ab5564ad93932badc2391034f61eafa4'}
两个实例化的方法。