1. 程式人生 > >面向對象——反射

面向對象——反射

用法示例 run elf exce () except out bar country

  • 反射:通過字符串的形式操作對象相關的屬性,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
    View Code
  • 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
    View Code
  • 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
    View Code

  • 技術分享圖片
     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>
    用法示例——類也是對象

面向對象——反射