Python | 学习type()方法动态创建类

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 dynamically created class.")

      DynamicClass = type("DynamicClass", (BaseClass,), {"new_attr": "This is a new attribute", "new_method": new_method})

      DynamicClass = type("DynamicClass", (BaseClass,), dict(test_demo='this is test',new_attr= "This is a new attribute", new_method= new_method))

      -------------------------

      注意 {} 和dict其实用法是一样的

      -------------------------

      obj = DynamicClass('testing')
      obj.base_method() # 父类方法
      print(obj.test_demo)# 这是一个属性
      print(obj.new_attr)# 这是一个属性
      obj.new_method()# 这是一个方法

复制代码
def init_method(self, name):
    self.name = name
    
def say_name(self):
    print(f"My name is {self.name}")

Person = type("Person", (), {"__init__": init_method, "say_name": say_name})

person_obj = Person("Alice")
person_obj.say_name()
相关推荐
一只鹿鹿鹿2 分钟前
信息化项目管理规范(参考Word文件)
java·大数据·运维·开发语言·数据库
XGeFei6 分钟前
python中子线程与主线程的关系
开发语言·python
Chase_______10 分钟前
【Java杂项】final 关键字详解:变量、方法、类限制与引用可变性
java·开发语言·python
Huangxy__17 分钟前
线程池的学习
学习
ruxingli19 分钟前
Golang iota详解
开发语言·后端·golang
小丶舟19 分钟前
6GB显卡跑Hermes Agent!开源AI自学习编程Agent实测
人工智能·学习·开源
我材不敲代码20 分钟前
Python venv 虚拟环境从入门到精通 + uv 高性能替代工具实战指南
开发语言·python·uv
Bechamz26 分钟前
大数据开发学习Day45
大数据·学习
l1t32 分钟前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程18-20
开发语言·python
磊 子38 分钟前
STL之deque和list以及两者与vector的对比
开发语言·c++·list