Python学习2-反射

"Python学习"

Posted by Mas9uerade on April 15, 2018

“上周简单地学习了Python的基础语法和API,整理一下加深理解和印象”

Python中的反射

Pyhthon可查类型、可反射。 反射的方式有:
1.type()查类型;


a = str("sssss")

print(type([]) )

print(type({}))

print(type(''))

print(type(0.0))

2.isinstance()查引用;

class Plant:
    life = 0
    pass
class Tree(Plant): pass                  # Dummy class derived from Plant
tree = Tree()                             # A new instance of Tree class

print("isinstance")
print (isinstance(tree, Tree))             # True
print (isinstance(tree, Plant))            # True
print (isinstance(tree, object) )          # True
print (type(tree) is Tree)                 # False
print (type(tree).__name__ == "instance")  # True
print (tree.__class__.__name__ == "Tree")  # True

3.issubclass()查继承;

print("isubclass")
print (issubclass(Tree, Plant))            # True
print (issubclass(Tree, object))           # False in Python 2
print (issubclass(int, object))            # True
#print (issubclass(tree, Plant))            # Error - tree is not a class

4.callable()是否可调用;


print("callable")
print(callable([1,2].pop))
print(callable([1,2].pop()))

5.dir()查包含的属性名;


print("Dir")
print(dir(3))
print(dir("HelloWorld"))
print(dir([1,2]))
print(dir(re))

  1. getattr() 第一个参数是对象实例obj,name是个字符串,是对象的成员函数名字或者成员变量,default当对象没有这个属相的时候就返回默认值,如果没有提供默认值就返回异常。
print("attribute")
print(getattr(tree, "life"))
#print(getattr(tree, "life?")) 没有就会报错
print(getattr(tree, "life?", None))