在元类的__call__中获取__init__的可选参数。

时间:2019-10-25 15:15:55

标签: python python-3.x metaprogramming

我需要跟踪类实例的值(以避免实例具有相同的值)。我编码了以下metaclass

class UniqueInstances(type):
    def __new__(mcs, name, bases, dct):
        dct['instancesAttrs'] = set()

        return super().__new__(mcs, name, bases, dct)

    def __call__(cls, *args):
        if args not in cls.instancesAttrs:
            cls.instancesAttrs.add(args)

            return super().__call__(*args)
        else:
            print("Warning: " +
                  "There is another instance of the class " +
                  "'{}' ".format(cls.__name__) +
                  "with the same attributes. The object was not created.")

            return None

因此,我无法创建两个具有相同值的实例,例如:

class Coordinate(metaclass=UniqueInstances):
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z


coor1 = Coordinate(0, 0, 0)
coor2 = Coordinate(0, 0, 0)  # Warning: There is another instance...

但是,我无法处理可选参数,例如:

class Coordinate(metaclass=UniqueInstances):
    def __init__(self, x, y, z=0):
        self.x = x
        self.y = y
        self.z = z

coor1 = Coordinate(0, 0)
coor2 = Coordinate(0, 0, 0) # no warning, but there are two objects with the same values

因为

print(Coordinate.instancesAttrs)  # {(0, 0), (0, 0, 0)}

所以,我想知道是否有可能在__call__方法中获得可选参数。

0 个答案:

没有答案