Python3元类:用于验证构造函数argumen

2024-04-25 07:40:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我本来打算用元类来验证Python3中的构造函数参数,但似乎__new__方法无法访问变量val,因为类{}尚未实例化。在

播种正确的方法是什么?在

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)

Tags: 方法selfnewdeftypeval函数参数python3
2条回答

wim is absolutely correct that this isn't a good use of metaclasses,但这当然是可能的(而且也很简单)。在

考虑如何创建类的新实例。你这样做:

A(123)

换句话说:通过调用类来创建实例。python允许我们通过定义^{} method来创建定制的可调用对象。所以我们要做的就是在元类中实现一个合适的__call__方法:

^{pr2}$

就这样。很简单,对吧?在

>>> A('foo')
<__main__.A object at 0x007886B0>
>>> A(123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "untitled.py", line 5, in __call__
    raise TypeError('val must be a string')
TypeError: val must be a string

... 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。python代码是duck-typed。只需记录您所期望的类似字符串的参数,将垃圾放入的用户将得到垃圾输出。在

相关问题 更多 >