《Python》反射内置函数(__str____repr__)

Posted 酒醉人醒

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《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实例

 

以上是关于《Python》反射内置函数(__str____repr__)的主要内容,如果未能解决你的问题,请参考以下文章

python26 封装 多态 常用的内置函数 `__str__` `__del__` 反射 动态导入模块

python3全栈开发-内置函数补充,反射,元类,__str__,__del__,exec,type,__call__方法

17 Apr 18 内置函数(isinstance,issubclass)反射 __str__ __del__ __call__ 元类

issubclass和isinstance,反射,内置方法

python 几个常用的内置函数

python-38-用于面向对象的内置函数