zoukankan      html  css  js  c++  java
  • 面向对象——反射

    • 反射:通过字符串的形式操作对象相关的属性,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>
      用法示例——类也是对象
  • 相关阅读:
    2019杭电多校训练(一)
    2019牛客多校训练(二)
    2019牛客多校训练(一)
    codeforces#1196F. K-th Path(最短路,思维题)
    codeforces#1108E2. Array and Segments (线段树+扫描线)
    codeforces#1183F. Topforces Strikes Back(数论)
    SPOJ
    2020年4月 第十一届蓝桥杯大赛个人赛(软件类)省级模拟赛
    Codeforces Round #634 (Div. 3)
    POJ
  • 原文地址:https://www.cnblogs.com/GraceZ/p/8137736.html
Copyright © 2011-2022 走看看