getattr方法的使用场景是在访问不存在的属性时,会触发该方法中的处理逻辑。尤其是在动态属性获取中结合 type()动态创建类有着良好的使用关系。
type()方法常用来判断属性的类别,而动态创建类不常使用,通过如下的几个实例来学习使用:
def say_hello(self):
print("Hello, I'm an instance of a dynamically created class!")
# 使用type函数创建类
MyClass = type("MyClass", (), {"hello": say_hello})
ttt = MyClass()
ttt.hello()
- 在这个示例中:
- 首先定义了一个函数 say_hello,它将作为类的方法。
- 然后使用 type 函数创建了一个名为 MyClass 的类。type 函数的参数分别是类名"MyClass",父类(这里为空,用()表示),以及类的属性和方法(这里是一个名为"hello"的方法,指向 say_hello 函数)。
- 最后创建了 MyClass 的一个实例 obj,并调用了 obj.hello()方法。
class BaseClass:
def __init__(self,name):
self.name=name
print(str(self.__class__.__name__)+' begin '+name)
def base_method(self):
print("This is a method from the base class.")
def new_method(self):
print("This is a new method added to the dynamicall