绑定方法与非绑定方法
绑定方法
绑定给谁就由谁来调用,谁来调用就把他当作一个参数自动传入
类中talk_info绑定给对象使用:
class People:
def __init__(self,name,age):
self.name = name
self.age = age
def talk_info(self):
print('222')
p = People('XX',20)
print(People.talk_info) # 用类去调用是当作普通函数使用的 <function People.talk_info at 0x0000018D815187C0>
print(p.talk_info) # 用对象去调用则为绑定方法 <bound method People.talk_info of <__main__.People object at 0x0000018D815F6150>>
People.talk_info(p) # 需要传入对象
p.talk_info() # 直接调用
将talk_info绑定给类使用:
class People:
def __init__(self,name,age):
self.name = name
self.age = age
@classmethod
def talk_info(cls): # cls和self都是一种命名习惯,cls作为第一个参数表示类本身
return cls('XX',20)
p = People.talk_info() # 不需要传对象了
和对象绑定方法一样:绑定给类就由类来调用,并将类作为第一个参数传入。
和对象绑定方法不同:当对象在调用类的绑定方法的时候,也会默认把类当作参数传递进去。
非绑定方法
不需要绑定类或者对象来使用,谁都可以用,没有自动传值的效果。
在python类中会默认给函数一个实例用于绑定给对象,而解除这个绑定关系就要用到@staticmethod方法
class People:
def __init__(self,name):
self.name = name
@staticmethod
def info(): # 直接去掉self就会报错,在前面加上@staticmethod
print('hello')
e = People('XX')
e.info() # hello
People.info() # hello
也可以传参:
class People:
def __init__(self,name):
self.name = name
@staticmethod
def info(x,y): # 直接去掉self就会报错,在前面加上@staticmethod
print('hello')
print(x,y)
e = People('XX')
e.info(20,50) # hello 20 50
People.info('cc','zz') # hello cc zz
绑定方法的应用:
没有类方法:
import setting
class People:
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def info(self):
print('Name:%s Age:%d Sex:%s'%(self.name,self.age,self.sex))
z = People(setting.name,setting.age,setting.sex)
y = People(setting.name,setting.age,setting.sex)
x = People(setting.name,setting.age,setting.sex)
w = People(setting.name,setting.age,setting.sex)
有类方法:
import setting
class People:
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
@classmethod
def from_con(cls):
obj = People(setting.name, setting.age, setting.sex)
return obj
def info(self):
print('Name:%s Age:%d Sex:%s'%(self.name,self.age,self.sex))
z = People.from_con()
y = People.from_con()
x = People.from_con()
w = People.from_con()
非绑定方法:
# 给每个人生成一个id号
import time
class People:
def __init__(self,name,age):
self.name = name
self.age = age
self.id = People.creat_id() # 自动生成id号
@staticmethod
def creat_id():
m = str(time.time()) # 根据时间不同创建值
return m
p1 = People('一花',20)
time.sleep(0.2)
p2 = People('二乃',21)
time.sleep(0.2)
p3 = People('三玖',22)
print(p1.id) # 1705463322.2089322
print(p2.id) # 1705463322.4089973
print(p3.id) # 1705463322.609788
..是我太天真了。学到这里就想做飞机大战小游戏。。好多码。。好多好多好多。。
。。以后再填个坑。。。