- 反射:通过字符串的形式操作对象相关的属性,python中一切皆对象(都可以使用反射)
- hasattr(object,name):判断object中有没有一个name字符串对应的方法或属性
- getattr(object, name, default=None)
-
1 def getattr(object, name, default=None): # known special case of getattr 2 """ 3 getattr(object, name[, default]) -> value 4 5 Get a named attribute from an object; getattr(x, ‘y‘) is equivalent to x.y. 6 When a default argument is given, it is returned when the attribute doesn‘t 7 exist; without it, an exception is raised in that case. 8 """ 9 pass
- setattr(x, y, v)
-
1 def setattr(x, y, v): # real signature unknown; restored from __doc__ 2 """ 3 Sets the named attribute on the given object to the specified value. 4 5 setattr(x, ‘y‘, v) is equivalent to ``x.y = v‘‘ 6 """ 7 pas
- delattr(x, y)
-
1 def delattr(x, y): # real signature unknown; restored from __doc__ 2 """ 3 Deletes the named attribute from the given object. 4 5 delattr(x, ‘y‘) is equivalent to ``del x.y‘‘ 6 """ 7 pass
-
1 class People: 2 country=‘China‘ 3 4 def __init__(self,name,age): 5 self.name=name 6 self.age=age 7 8 def talk(self): 9 print(‘%s is talking‘ %self.name) 10 obj=People(‘egon‘,18) 11 #通常情况下: 12 # print(obj.name) #egon 13 # print(obj.talk)#<bound method People.talk of <__main__.People object at 0x000000000287ACC0>> 14 # 15 # choice = input("==>:")##choice=‘name‘ 16 # print(object.choice)#object.‘name‘,报错 17 #字符串映射 18 19 #检测是否含有某属性 20 # print(hasattr(obj,‘name‘)) #True 21 # print(hasattr(obj,‘talk‘)) #True 22 # print(hasattr(obj,‘run‘))#False 23 24 #获取属性 25 # print(getattr(obj,‘name‘))#egon 26 # print(getattr(obj,‘run‘))#报错 27 # print(getattr(obj,‘run‘,None))#None 28 # fun = getattr(obj,‘talk‘) 29 # fun()#egon is talking 30 31 #设置属性 32 setattr(obj,‘sex‘,‘male‘) #obj.sex = male 33 print(obj.sex)#male 34 setattr(obj,‘show_name‘,lambda self : self.name+‘_s‘)#设置方法 35 print(obj.show_name(obj))#egon_s 36 print(obj.__dict__) 37 #{‘name‘: ‘egon‘, ‘age‘: 18, ‘sex‘: ‘male‘, ‘show_name‘: <function <lambda> at 0x0000000001CF2E18>} 38 39 #删除属性 40 delattr(obj,‘age‘) 41 delattr(obj,‘show_name‘) 42 print(obj.__dict__)#{‘name‘: ‘egon‘, ‘sex‘: ‘male‘} 43 delattr(obj,‘age‘)#不存在,则报错
class Foo: staticField = ‘old boy‘ def __init__(self): self.name = ‘wupeiqi‘ @classmethod def func(self): return ‘func‘ @staticmethod def bar(): return ‘bar‘ print(getattr(Foo,‘staticField‘))#old boy print(getattr(Foo,‘func‘))#<bound method Foo.func of <class ‘__main__.Foo‘>> print(getattr(Foo,‘bar‘))#<function Foo.bar at 0x0000000001E84510>
面向对象——反射
Posted GraceZen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象——反射相关的知识,希望对你有一定的参考价值。
以上是关于面向对象——反射的主要内容,如果未能解决你的问题,请参考以下文章