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()
相关推荐
iAm_Ike2 分钟前
c++如何利用std--chrono计算文件操作的微秒级耗时性能分析【详解】
jvm·数据库·python
七颗糖很甜2 分钟前
卫星通信遇到“太空天气”会怎样---电离层闪烁对卫星通信的影响
大数据·python·算法
高木木的博客5 分钟前
数字架构智能化测试平台(2)--AI DevOps测试流程框架
python·llm·fastapi·cicd
2401_880071405 分钟前
如何检查SQL注入漏洞覆盖率_使用漏洞管理平台监控
jvm·数据库·python
X56616 分钟前
Go语言怎么做六边形架构_Go语言六边形架构教程【简明】
jvm·数据库·python
m0_624578597 分钟前
HTML标签不区分大小写吗_标签大小写规范建议【解答】
jvm·数据库·python
CLX05059 分钟前
SQL如何计算字符串的长度:LENGTH与CHAR_LENGTH用法
jvm·数据库·python
Frank_refuel9 分钟前
C++之STL->string类的使用和实现
java·开发语言·c++
2301_7820404510 分钟前
mysql如何转换MyISAM表到InnoDB_使用ALTER TABLE语句方法
jvm·数据库·python
feifeigo12310 分钟前
图像重建中软阈值方法的原理和MATLAB实现
开发语言·matlab