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()
相关推荐
Irene19911 小时前
Python 卸载与安装(以卸载3.13.3,装3.13.13为例)
python
予早1 小时前
使用 pyrasite-ng 和 guppy3 做内存分析
python·内存分析
hef2886 小时前
如何生成特定SQL的AWR报告_@awrsqrpt.sql深度剖析单条语句性能
jvm·数据库·python
Jinkxs7 小时前
从语法纠错到项目重构:Python+Copilot 的全流程开发效率提升指南
python·重构·copilot
技术专家7 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
m0_488913017 小时前
万字长文带你梳理Llama开源家族:从Llama-1到Llama-3,看这一篇就够了!
人工智能·学习·机器学习·大模型·产品经理·llama·uml
段一凡-华北理工大学7 小时前
【大模型+知识图谱+工业智能体技术架构】~系列文章01:快速了解与初学入门!!!
人工智能·python·架构·知识图谱·工业智能体
IT小Qi7 小时前
iperf3网络测试工具
网络·python·测试工具·信息与通信·ip
以神为界7 小时前
Python入门实操:基础语法+爬虫入门+模块使用全指南
开发语言·网络·爬虫·python·安全·web
xcjbqd07 小时前
Python API怎么加Token认证_JWT生成与验证拦截器实现
jvm·数据库·python