python是先运行metaclass还是先有类属性解析
答案
先有 “类属性”,再有 “运行 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
以上就是python是先运行metaclass还是先有类属性解析的详细内容,更多关于python metaclass类属性的资料请关注脚本之家其它相关文章!
相关文章
Python随机函数random随机获取数字、字符串、列表等使用详解
这篇文章主要介绍了Python随机函数random使用详解包含了Python随机数字,Python随机字符串,Python随机列表等,需要的朋友可以参考下2021-04-04
Python plt 利用subplot 实现在一张画布同时画多张图
这篇文章主要介绍了Python plt 利用subplot 实现在一张画布同时画多张图,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2021-02-02
Python读取Windows和Linux的CPU、GPU、硬盘等部件温度的读取方法
本文详细介绍了如何使用Python在Windows和Linux系统上通过OpenHardwareMonitor和psutil库读取CPU、GPU等部件的温度,包括Windows下的两种方法以及Linux下的简单实现,感兴趣的小伙伴跟着小编一起来看看吧2025-02-02
pandas读取excel,txt,csv,pkl文件等命令的操作
这篇文章主要介绍了pandas读取excel,txt,csv,pkl文件等命令的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2021-03-03
用Python做的数学四则运算_算术口算练习程序(后添加减乘除)
这篇文章主要介绍了用Python做的数学四则运算_算术口算练习程序(后添加减乘除),需要的朋友可以参考下2016-02-02


最新评论