0、函数与方法
在类内部定义的函数,由对象来调用,它就是方法,如果是类直接调用,它还是函数 from types import MethodType, FunctionType def test(): pass print(isinstance(test, FunctionType)) # True print(isinstance(test, MethodType)) # False class Foo(): def test(self): pass foo = Foo()
#foo.test()由对象调用,为方法 print(isinstance(foo.test, FunctionType)) # False print(isinstance(foo.test, MethodType)) # True
#Foo.test('xxxx')由类直接调用,为函数 print(isinstance(Foo.test, FunctionType)) # True print(isinstance(Foo.test, MethodType)) # False
1、反射
反射:通过字符串来反射/映射到对象/类的属性上(只要是 . 能访问属性的操作,全都可以使用反射进行操作) class People: def __init__(self,name,age): self.name=name self.age=age def run(self): print('%s is running' %self.name) obj=People('lww',18) # print(obj.__dict__) # print(obj.name) #obj.__dict__['name'] # obj.name='EGON' #obj.__dict__['name']='EGON' # # del obj.name # del obj.__dict__['name'] # # obj.sex='male' #obj.__dict__['sex']='male' # attr=input('>>>: ').strip() #attr='name' # obj.'name' 1. hasattr(object, name) 说明:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的) # print(hasattr(obj,'name')) # 'name' in obj.__dict__ 2. getattr(object, name,default) # print(getattr(obj,'name')) # obj.__dict__['name'] # print(getattr(obj,'xxx',None)) # obj.__dict__['xxx'] 3. setattr(object, name, value) # setattr(obj,'name','EGON') #obj.__dict__['name']='EGON' # setattr(obj,'xxx',1111) #obj.__dict__['xxx']=111 # print(obj.name) # print(obj.__dict__) 4. delattr(object, name) # delattr(obj,'name') # print(obj.__dict__) 5.操作模块 # import os # os.remove # print(hasattr(os,'remove'))
2、__str__
# __str__: 在对象被打印时自动触发,可以用来定义对象被打印时的输出信息 # 注意:必须返回一个字符串类型的值, class People: def __init__(self, name, age): self.name = name self.age = age def __str__(self): # print('run..........') return '<name:%s age:%s>' % (self.name, self.age) obj1 = People('egon', 18) print(obj1) # print(obj1.__str__()) obj2=list([1,2,3]) print(obj2)
3、__del__
# __del__: 在对象被删除时先自动触发该方法,可以用来回收对象以外其他相关资源,比如系统资源 class Foo: def __init__(self,x,filepath,encoding='utf-8'): self.x=x self.f=open(filepath,'rt',encoding=encoding) def __del__(self): print('run.....') # 回收对象关联的其他资源 self.f.close() obj=Foo(1,'a.txt') # del obj print('主===========>')
4、isinstance(obj,cls)和issubclass(sub,super)
isinstance(obj,cls)检查是否obj是否是类 cls 的对象
class Foo(object):
pass
obj = Foo()
instance(obj, Foo)
issubclass(sub, super)检查sub类是否是 super 类的派生类(子类)
class Foo(object):
pass
class Bar(Foo):
pass
issubclass(Bar, Foo)
5、绑定方法与非绑定方法
# 一: 绑定方法:绑定给谁就应该由谁来调用,谁来调用就会将谁当做第一个参数传入 # 1. 绑定给对象的方法: 类中定义的函数默认就是绑定给对象的 # 2. 绑定给类的方法classmethod: 为类中定义的函数加上一个装饰器classmethod # 二: 非绑定方法staticmethod: 既不与类绑定,又不与对象绑定,意味着对象和类都可以来调用,无论谁来调用都是一个普通的函数,没有自动传值的效果 import settings class MySql: def __init__(self, ip, port): self.id = self.create_id() self.ip = ip self.port = port def tell_info(self): print('<id:%s ip:%s port:%s>' % (self.id, self.ip, self.port)) @classmethod def from_conf(cls): return cls(settings.IP, settings.PORT) @staticmethod def create_id(): import uuid return uuid.uuid4() # obj1=MySql('1.1.1.1',3306) # obj1.tell_info() obj2 = MySql.from_conf() obj2.tell_info()