《Python》反射、内置函数(__str__、__repr__)

一、反射

   通过字符串的形式操作对象相关的属性。(使用字符串数据类型的变量名来获取这个变量的值)

    Python中的一切事物都是对象(都可以使用反射)

#hasattr

def hasattr(*args, **kwargs): # real signature unknown
    """
    Return whether the object has an attribute with the given name.
    
    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass



#getattr

def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value
    
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass



#setattr

def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.
    
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass



#delattr

def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.
    
    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass
反射的4种方法源码

  

# 反射类中的变量: 静态属性、类方法、静态方法
class Foo:
    school = 'oldboy'
    country = 'china'
    language = 'chiness'

    @classmethod
    def class_method(cls):
        print(cls.school)

    @staticmethod
    def static_method():
        print('in staticmethod')

    def wahaha(self):
        print('wahaha')

print(Foo.school)   # oldboy
print(Foo.country)  # china
print(Foo.language) # chiness

# 判断实现
inp = input('>>>')
if inp == 'school': print(Foo.school)       # oldboy
elif inp == 'country': print(Foo.country)   # china
elif inp == 'language': print(Foo.language) # chiness

# 反射实现
while 1:
    inp = input('>>>')      # 输school,打印oldboy    输country,打印china    输language,打印chiness
    print(getattr(Foo,inp))

# 解析getattr方法
print(getattr(Foo,'school'))   # oldboy
Foo.class_method()              # oldboy
print(getattr(Foo,'class_method'))  # <bound method Foo.class_method of <class '__main__.Foo'>>
getattr(Foo,'class_method')()  # oldboy     相当于:Foo.class_method()
getattr(Foo,'static_method')() # in staticmethod    相当与:Foo.static_method()
getattr实例

猜你喜欢

转载自www.cnblogs.com/yzh2857/p/9567252.html