绑定方法有两种:
一种是定义在类里给对象的绑定方法,另外一种是绑定给类使用。
我们来看一下用classmethod,如何将方法绑定给类使用的。
#在setting文件中用来个属性我们来调用它 NAME='monicx' AGE=23 #===========end================== import setting class People: def __init__(self,name,age): self.name=name self.age=age def tell(self): print('%s,%s'%(self.name,self.age)) @classmethod def from_conf(cls): return cls(setting.NAME,setting.AGE) p1=People.from_conf() p1.tell()
用@classmethod装饰过的方法谅是绑定给类的方法,有个细节,此时方法里面默认的第一参数名不再为self而是变为cls。
staticmethod
那么有人会想,有没有一种方法,在类里面定义,即可以给类用,又可以给对象使用的呢!!!
有,它就是非绑定方法,也称为静态方法。在类里定义的方法前加上@staticmethod装饰器即可。
解决一个对象和类都能获取一个id的问题:
import hashlib import time class People: def __init__(self,name,age): self.name=name self.age=age def tell(self): print('%s,%s'%(self.name,self.age)) @staticmethod def create_id(): m = hashlib.md5() m.update(str(time.clock()).encode('utf-8')) return m.hexdigest() obj=People('xxx','22') print(obj.create_id()) print(People.create_id())这样即可让类来获取一个id,也可以通过对象获取一个id