类中函数的装饰器


#类中函数的装饰器
面向对象补充:
类中定义的函数分为两大类(绑定&非绑定):
5.绑定方法于非绑定方法:
classmethod:
staticmethod:
5.1绑定方法:
特殊之处:绑定给谁就应该由谁来调用,谁来调用就会将谁当作第一个参数传入
5.1.1 绑定给对象的方法:类中定义的函数默认就是绑定给对象的
绑定给对象的方法,类也可以调用,但是类来调用就是一个普通函数,没有自动传值效果
5.1.2 绑定给类的方法:为类中定义的函数加上一个装饰器classmethod
绑定给类的应该由类来调用,对象也可以调用,对象调用就是把对象的类当作参数自动传值
与跟绑定的类自己调用是一样的

5.2非绑定方法:就是一个普通的函数。
特殊之处: 既不与类绑定,又不与对象绑定,意味着对象和类都可以来调用,无论谁来调用都是一个
普通的函数,没有自动传值的效果
非绑定方法:为类中定义的函数加上一个装饰器staticmethod,取消自动传参
class Foo:
def f1(self):
print("f1",self)
@classmethod #绑定给类
def f2(cls):
print("f2",cls)
@staticmethod #解绑定
def f3(xx):
print("f3",xx)
#调用
obj=Foo()
obj.f1()#f1 <__main__.Foo object at 0x00000184BFAD6C18>
obj.f2()#f2 <class '__main__.Foo'>
Foo.f2()#f2 <class '__main__.Foo'>
Foo.f3(1)#f3 1
obj.f3(3)#f3 3




import settings #名settings的py文件里面有信息IP=1.1.1.1 PORT=3360
class MySQL:
def __init__(self,ip,port,id):
self.id=self.creat_id()
self.ip=ip
self.port=port

def tell_info(self):
print("<ip:%s port:%s id:%s>"%(self.ip,self.port,self.id))

@classmethod
def form_conf(cls):
return cls(settings.IP,settings.PORT)

@staticmethod
def creat_id():
import uuid
return uuid.uuid4()
#方法一
obj1=MySQL('10.01.11',3360)
obj1.tell_info()

# 方法二
obj2=MySQL.form_conf()
obj2.tell_info()




2.反射(hasattr,seratter,getattr,delattr四个装饰器的使用)
反射:指的是通过字符串来操作属性

# class Foo:
# def __init__(self,name,age):
# self.name=name
# self.age=age
# def tell_info(self):
# print("%s %s"%(self.name,self.age))
# obj=Foo("egon",18)

hasattr:
# #hasattr
# print(hasattr(obj,"name"))#True obj.name
# print(hasattr(obj,"tell_info"))#True obj.tell_info

seratter:
# #getattr
# res=getattr(obj,"name")#res=obj.name
# print(res)#egon
# res=getattr(obj,"xxx",None)
# print(res)#None

getattr:
# #setatter
# setattr(obj,"egon",38)
# setattr(obj,"sex",'male')#添加
# print(obj.__dict__)#{'name': 'egon', 'age': 18, 'egon': 38, 'sex': 'male'}
# print(obj.sex)#male

delattr:
# #delattr
# delattr(obj,"name")#删除
# print(obj.__dict__)#{'age': 18, 'egon': 38, 'sex': 'male'}



3.内置方法:
__str__方法:

#__str__内置的函数 只在打印时触发 必须有返回值
class PeoPle:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return "<%s:%s>"%(self.name,self.age)

peo=PeoPle("egon",18)
print(peo)#print(peo.__str__())



__del__方法:

#__del__会在对象被删除时自动触发执行,用来在对象被删除前回收系统资源
class Foo:
def __init__(self,x,y,db):
self.x=x
self.y=y
self.db=db

def __del__(self):
print("==>")
obj=Foo()
del obj
print("其他代码")
原文地址:https://www.cnblogs.com/yanhui1995/p/9852722.html