Skip to main content
 首页 » 编程设计

Python3 元类 : use to validate constructor argument

2025年05月04日22kuangbin

我计划在 Python3 中使用元类来验证构造函数参数,但似乎 __new__ 方法无法访问变量 val,因为类 A() 还没有被实例化。

Sow 正确的做法是什么?

class MyMeta(type): 
    def __new__(cls, clsname, superclasses, attributedict): 
        print("clsname: ", clsname) 
        print("superclasses: ", superclasses) 
        print("attributedict: ", attributedict) 
        return type.__new__(cls, clsname, superclasses, attributedict) 
 
class A(metaclass=MyMeta): 
    def __init__(self, val): 
        self.val = val 
 
A(123) 

请您参考如下方法:

... it seems __new__method has no access to the variable val, because the class A() has not been instantiated yet.

没错。

So what's the correct way to do it?

不适用于元类。

元类用于摆弄类对象本身的创建,而您要做的是与类的实例相关。

最佳实践:根本不要对 val 进行类型检查。 Pythonic 代码是 duck-typed .只需记录您期望一个类似字符串的参数,然后将垃圾放入的用户将垃圾取出。