python是先运行metaclass还是先有类属性解析

作者:ponponon 时间:2022-02-10 23:24:48 

答案

先有 “类属性”,再有 “运行 metaclass”

# 定义一个元类
class CustomMetaclass(type):
   def __new__(cls, name, bases, attrs):
       print('> cls', cls)
       print('> name', name)
       print('> attrs', attrs)
       print('> cls dict', cls.__dict__)
       # 在创建类时修改属性
       new_attrs = {}
       for attr_name, attr_value in attrs.items():
           if isinstance(attr_value, str):
               new_attrs[attr_name] = attr_value.upper()
           else:
               new_attrs[attr_name] = attr_value
       obj = super().__new__(cls, name, bases, new_attrs)
       print(obj.__dict__)
       print(type(obj))
       return obj
# 使用元类创建类
class MyClass(metaclass=CustomMetaclass):
   name = 'John'
   age = 30
   greeting = 'Hello'
   def say_hello(self):
       print(self.greeting)
# 创建类的实例并调用方法
obj = MyClass()
print(obj.name)         # 输出: 'JOHN'
print(obj.age)          # 输出: 30
obj.say_hello()         # 输出: 'Hello'

输出结果

> cls <class '__main__.CustomMetaclass'>
> name MyClass
> attrs {'__module__': '__main__', '__qualname__': 'MyClass', 'name': 'John', 'age': 30, 'greeting': 'Hello', 'say_hello': <function MyClass.say_hello at 0x1025c2200>}
> cls dict {'__module__': '__main__', '__new__': <staticmethod(<function CustomMetaclass.__new__ at 0x1025c2290>)>, '__doc__': None}
{'__module__': '__MAIN__', 'name': 'JOHN', 'age': 30, 'greeting': 'HELLO', 'say_hello': <function MyClass.say_hello at 0x1025c2200>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}
<class '__main__.CustomMetaclass'>
JOHN
30

来源:https://segmentfault.com/a/1190000043839540

标签:python,metaclass,类属性
0
投稿

猜你喜欢

  • python反转单链表算法题

    2023-04-02 04:26:49
  • python如何将图片生成视频MP4

    2023-10-19 09:25:37
  • python基本语法练习实例

    2021-02-25 06:50:07
  • Python学习之异常中的finally使用详解

    2021-09-08 02:21:38
  • 用python实现将数组元素按从小到大的顺序排列方法

    2022-01-07 22:03:25
  • python列表推导式入门学习解析

    2022-04-25 14:28:00
  • Python Requests安装与简单运用

    2023-09-26 22:02:15
  • Python Tkinter简单布局实例教程

    2021-03-08 13:41:23
  • Ubuntu20下的Django安装的方法步骤

    2022-05-01 09:07:24
  • 基于OpenCV目标跟踪实现人员计数器

    2022-11-17 15:04:03
  • jupyter notebook实现显示行号

    2022-11-20 03:51:40
  • 如何使用postman(新手入门)

    2023-06-12 14:00:31
  • Python递归函数特点及原理解析

    2023-12-02 19:40:40
  • Python基于回溯法子集树模板实现图的遍历功能示例

    2021-10-29 15:20:31
  • PHP面向对象程序设计高级特性详解(接口,继承,抽象类,析构,克隆等)

    2023-11-23 11:35:00
  • 对pandas replace函数的使用方法小结

    2022-07-04 15:20:24
  • python GUI库图形界面开发之PyQt5中QWebEngineView内嵌网页与Python的数据交互传参详细方法实例

    2021-07-28 18:28:45
  • Python pywifi ERROR Open handle failed问题及解决

    2021-01-16 03:54:28
  • matplotlib更改窗口图标的方法示例

    2023-01-15 17:55:30
  • keras做CNN的训练误差loss的下降操作

    2023-09-03 07:41:07
  • asp之家 网络编程 m.aspxhome.com