Python 获取uuu init';s optionals args在元类中';呼叫__
我需要跟踪类实例的值(以避免实例具有相同的值)。我编写了以下Python 获取uuu init';s optionals args在元类中';呼叫__,python,python-3.x,metaprogramming,Python,Python 3.x,Metaprogramming,我需要跟踪类实例的值(以避免实例具有相同的值)。我编写了以下元类 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 c
元类
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
但是,我不能处理可选参数,例如:
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)}
所以,我想知道是否有可能在
\uuuuuuuuuuuuuuuuuu
方法中获取可选参数。可选参数是kwargs。@Daniel,def\uuuuuuuuuu调用(cls,*args,**kwargs):print(kwargs)
是{/code>