面向对象进阶2
Posted liuhongshuai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象进阶2相关的知识,希望对你有一定的参考价值。
1,反射
反射 用字符串的名字去操作变量
#反射 用字符串的名字去操作变量 #hasattr getattr delattr setattr # class A: # price=20 # def __init__(self,name,age): # self.name=name # self.age=age # def func(self): # print(‘in func‘) # @classmethod # def func2(cls): # print(‘in func2‘) #hasattr判断对象或类是否具有指定属性和方法 # print(hasattr(A,‘price‘)) # print(hasattr(A,‘func‘)) # alex=A(‘alex‘,20) # print(hasattr(alex,‘func‘)) #getattr指定类或对象的属性和方法 # print(A.price) # print(getattr(A,‘price‘))#反射类的属性 # # print(getattr(A,‘abc‘)) # print(getattr(A,‘abc‘,‘没有这个属性‘)) # A.func2() # getattr(A,‘func2‘)()#反射类的方法 # # if hasattr(A,‘func2‘): # getattr(A,‘func2‘)() # # a=A(‘alex‘,20) # # print(a.name) # print(getattr(a,‘name‘))#反射对象的属性 # # a.func() # getattr(a,‘func‘)()#反射对象的方法 # # 反射模块的属性与方法 # import time # print(getattr(time,‘time‘)()) # setattr设置类或对象的属性和方法 # class A:pass # a=A() # setattr(a,‘name‘,‘alex‘) # print(a.name) # setattr(A,‘name‘,‘yuan‘) # print(A.name) # print(a.name) # delattr删除类或对象的属性和方法 # delattr(A,‘price‘) # delattr(a,‘price‘) # print(a.name)#报错 # --------------------------------------- #反射当前模块成员 # import sys # def func(): # print(‘in func‘) # this_module=sys.modules[__name__] # if hasattr(this_module,‘func‘): # res=getattr(this_module,‘func‘) # res()
2,类的内置方法
#类的内置方法 #双下方法 # obj.__str__ obj.__repr__() # class Teacher: # def __init__(self,name,salary): # self.name=name # self.salary=salary # def __str__(self): # return ‘Teacher object: {}‘.format(self.name) # # def __repr__(self): # return str(self.__dict__) # # def func(self): # return ‘welcome‘ # # alex=Teacher(‘alex‘,8000) # #打印一个对象时,就是在调用__str__方法,找不到__str__,再找__repr__ # #__repr__可做__str__的备胎 # print(alex) #str(alex)#‘%s‘%obj 都是在调用__str__ # print(repr(alex)) # print(‘%r‘%alex)#调用__repr__ # __format__ # format_dict={ # ‘nat‘:‘{obj.name}-{obj.addr}-{obj.type}‘, # ‘tna‘:‘{obj.type}-{obj.name}-{obj.addr}‘, # ‘tan‘:‘{obj.type}-{obj.addr}-{obj.name}‘, # } # class School: # def __init__(self,name,addr,type): # self.name=name # self.addr=addr # self.type=type # def __format__(self, format_spec): # if not format_spec or format_spec not in format_dict: # format_spec=‘nat‘ # fmt=format_dict[format_spec] # return fmt.format(obj=self) # s=School(‘清华大学‘,‘北京‘,‘公立‘) # print(format(s,‘nat‘)) # print(format(s,‘tan‘)) # print(format(s,‘tna‘)) # print(format(s,‘xxx‘)) #__doc__ # class Foo: # ‘‘‘ # 这是描述信息 # ‘‘‘ # pass # class Bar(Foo):pass # print(Foo.__doc__) # b=Bar() # print(b.__doc__)#__doc__不能继承 #__len__ # class Classes: # def __init__(self,name): # self.name=name # self.student=[] # def __len__(self): # return len(self.student) # # s=Classes(‘python‘) # s.student.append(‘alex‘) # s.student.append(‘yuan‘) # print(len(s)) # __hash__ # class A: # def __init__(self): # self.a=1 # self.b=2 # def __hash__(self): # return hash(str(self.a)+str(self.b)) # # def __eq__(self, other): # if self.a==other.a and self.b==other.b: # return True # a=A() # print(hash(a)) # b=A() # print(a==b) #__del__ #析构函数 在删除一个对象之前进行收尾工作 # class A: # def __init__(self,name): # self.name=name # def __del__(self): # print(‘执行删除操作了‘) # # # a=A(‘alex‘) # print(‘********‘) # del a # print(‘=============‘) #__call__ # class A: # def __init__(self,name): # self.name=name # def __call__(self, *args, **kwargs): # print(‘--->‘,self.name) # a=A(‘alex‘) # a()#执行类的__call__方法 # class A:pass # class B(A):pass # a=A() # print(isinstance(a,A))#对象与类 # print(issubclass(B,A))#子类与父类 # print(issubclass(A,B)) #getitem setitem delitem 在以字典方式 获取 设置 删除时触发 # class Foo: # def __init__(self,name,age,sex): # self.name=name # self.age=age # self.sex=sex # # def __getitem__(self, item): # print(‘正在获取‘) # if hasattr(self,‘item‘): # return self.__dict__[‘item‘] # def __setitem__(self, key, value): # print(‘正在设置‘) # self.__dict__[key]=value # # def __delitem__(self, key): # print(‘正在删除‘) # self.__dict__.pop(key)#del self.__dict__[key] # alex=Foo(‘alex‘,20,‘男‘) # alex[‘name‘] # alex[‘hobby‘]=‘IT‘ # del alex[‘hobby‘] # print(alex.hobby)#报错 #元类type # class Foo: # pass # f=Foo() # print(type(f))#<class ‘__main__.Foo‘> # print(type(Foo))#<class ‘type‘> #利用type创建类 # def __init__(self,name,age): # self.name=name # self.age=age # def func(self): # print(‘=========‘) # # Foo=type(‘Foo‘,(object,),{‘x‘:1,‘__init__‘:__init__,‘func‘:func}) # print(Foo)#<class ‘__main__.Foo‘> # print(Foo.__dict__) # # f=Foo(‘alex‘,20) # print(f.x,f.name,f.age) # f.func() # __init__初始化方法 #__new__构造方法 # class A: # def __init__(self): # self.x=1 # print(‘in init func‘) # def __new__(cls, *args, **kwargs): # print(‘in new func‘) # return object.__new__(A,*args,**kwargs) # a=A()#构造方法执行是由创建对象触发的 # print(a) #单例模式 # class Singleton: # def __new__(cls, *args, **kwargs): # if not hasattr(cls,‘_instance‘): # cls._instance=object.__new__(cls,*args,**kwargs) # return cls._instance # s1=Singleton() # s2=Singleton() # s1.a=10 # print(s1.a,s2.a) # print(s1==s2) # print(id(s1),id(s2)) # print(s1 is s2)
以上是关于面向对象进阶2的主要内容,如果未能解决你的问题,请参考以下文章