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()
相关推荐
婷婷_1721 分钟前
【PCIe 验证每日学习・Day22】PCIe 拓扑结构与 Switch / 桥片转发全解析
网络·学习·程序人生·芯片·pcie·pcie学习·pcie 拓扑
落痕的寒假2 分钟前
[深度学习] 大模型学习7-多模态大模型全景解析
人工智能·深度学习·学习
纤纡.5 分钟前
基于 PyTorch 手动实现 CBOW 词向量训练详解
人工智能·pytorch·python·深度学习
词元Max8 分钟前
2.5 Python 类型注解与运行时类型检查
开发语言·python
沪漂阿龙10 分钟前
深度解析Pandas数据组合:从concat到merge,打通你的数据处理任督二脉
python·数据分析·pandas
童园管理札记16 分钟前
2026实测|GPT-4.5+Agent智能体:3小时搭建企业级客服系统,附完整源码与部署教程(一)
经验分享·python·深度学习·重构·学习方法
墨^O^23 分钟前
进程与线程的核心区别及 Linux 启动全过程解析
linux·c++·笔记·学习
寒秋花开曾相惜23 分钟前
(学习笔记)3.9 异质的数据结构(3.9.1 结构)
c语言·网络·数据结构·数据库·笔记·学习
福楠23 分钟前
现代C++ | C++14甜点特性
linux·c语言·开发语言·c++
大飞记Python24 分钟前
【2026更新】Python基础学习指南(AI版)——安装
自动化测试·python·ai编程