1.元类type
type 获取对象从属于的类
python 中 一切皆对象, 类在某种意义上也是一个对象, python中自己定义的类, 以及大部分内置类, 都是由type元类(构建类)实例化得来的
type 与 object 的关系
print(type(object))
object类是type类的一个实例
object类是type类的父类
2.反射
程序对自己内部代码的一种自省方式
反射是什么
通过字符串去操作对象的方式
具体方法
hasattr
getattr
setattr
delattr
反射角度
实例对象
# obj = A('赵海狗',47)
class A:
country = "中国"
def __init__(self, name, age):
self.name = name
self.age = age
def func(self):
print("in A func")
obj = A("赵海狗", 47)
print(hasattr(obj,"name"))
print(hasattr(obj,"country"))
print(hasattr(obj,"func"))
print(getattr(obj,"name"))
print(getattr(obj,"country"))
f = getattr(obj,"func")
f()
print(getattr(obj, "sex", None))
obj.sex = "公"
setattr(obj, "sex", "公")
print(obj.__dict__)
delattr(obj,"name")
print(obj.__dict__)
类
class A:
country = "中国"
def __init__(self, name, age):
self.name = name
self.age = age
def func(self):
print(self)
print("in A func")
if hasattr(A,"country"):
print(getattr(A, "country"))
if hasattr(A, "func"):
obj = A("赵海狗", 26)
getattr(obj, "func")()
# 和下方方法一样 区别在于一个对象反射,一个类反射,一个不用传参, 一个需要传参
getattr(A, "func")(obj)
本模块
a = 666
def func1():
print("in 本模块这个对象")
import sys
print(sys.modules[__name__])
print(getattr(sys.modules[__name__], "a"))
getattr(sys.modules[__name__], "func1")()
练习题
1.使用反射依次调用所有函数
def func1():
print("in func1")
def func2():
print("in func2")
def func3():
print("in func3")
def func4()