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()
相关推荐
复业思维2024010820 小时前
Altium Designer (24.2.2)中更改库以及保持器件参数不变
笔记·学习·硬件工程
CDwenhuohuo20 小时前
uniapp去掉手机状态栏 全屏展示
开发语言·javascript·uni-app
巧克力味的桃子20 小时前
进制转换3 学习笔记
笔记·学习
小钻风336620 小时前
软件测试: 从入门到实践(接口自动化)
软件测试·python·自动化
别多香了20 小时前
Python 基础--循环判断&字符串
开发语言·python
老歌老听老掉牙20 小时前
使用 Matplotlib 自定义坐标轴字体及刻度样式详解
python·matplotlib
Purple Coder20 小时前
人工智能学习路线
学习
小帅学编程20 小时前
Spring(侧重注解开发)
java·学习·spring
早点睡觉好了20 小时前
JAVA中基本类型和包装类型的区别
java·开发语言
爱喝水的鱼丶20 小时前
SAP-ABAP:在SAP世界里与特殊字符“斗智斗勇”:一份来自实战的避坑指南
运维·服务器·数据库·学习·sap·abap·特殊字符