我正在尝试掌握(开始;))以了解如何在 Python 3 上正确使用装饰器和描述符。我想出了一个想法,我试图弄清楚如何对其进行编码。
我希望能够创建一个用某些“函数” B或“类” B装饰的类A,它允许我在将A上的属性声明为某种类型的组件并在 A 上分配值之后创建A的实例魔法功能。例如: __init__
组件化是允许我声明类 Vector的某些“函数B ”或“B 类” 。我声明x和y是这样的组件(浮点数):
@componentized
class Vector:
x = component(float)
y = component(float)
def __init__ (self, x, y):
self.x = x
self.y = y
我的想法是能够做到这一点:
v = Vector(1,2)
v.x #returns 1
但主要目标是我想为每个标记的组件(浮动)属性执行此操作:
v.xy #returns a tuple (1,2)
v.xy = (3,4) #assigns to x the value 3 and y the value 4
我的想法是创建一个装饰器@componentized来覆盖__getattr__
和__setattr__
魔术方法。排序这样的:
def componentized(cls):
class Wrapper(object):
def __init__(self, *args):
self.wrapped = cls(*args)
def __getattr__(self, name):
print("Getting :", name)
if(len(name) == 1):
return getattr(self.wrapped, name)
t = []
for x in name:
t.append(getattr(self.wrapped, x))
return tuple(t)
@componentized
class Vector(object):
def __init__(self, x, y):
self.x = x
self.y = y
它有点奏效,但我认为我不太明白发生了什么。因为当我尝试进行分配并覆盖__setattr__
魔术方法时,即使我正在实例化类,它也会被调用。以下示例中的两次:
vector = Vector(1,2)
vector.x = 1
我怎么能实现这种行为?
提前致谢!如果需要更多信息,请随时询问!
编辑:
按照@Diego的回答,我设法做到了:
def componentized(cls):
class wrappedClass(object):
def __init__(self, *args, **kwargs):
t = cls(*args,**kwargs)
self.wrappedInstance = t
def __getattr__(self, item):
if(len(item) == 1):
return self.wrappedInstance.__getattribute__(item)
else:
return tuple(self.wrappedInstance.__getattribute__(char) for char in item)
def __setattr__(self, attributeName, value):
if isinstance(value, tuple):
for char, val in zip(attributeName, value):
self.wrappedInstance.__setattr__(char, val)
elif isinstance(value, int): #EMPHASIS HERE
for char in attributeName:
self.wrappedInstance.__setattr__(char, value)
else:
object.__setattr__(self, attributeName, value)
return wrappedClass
并且有一个像这样的类Vector:
@componentized
class Vector:
def __init__ (self, x, y):
self.x = x
self.y = y
它的行为就像我想要的那样,但我仍然不知道如何实现:
x = component(float)
y = component(float)
在Vector类中以某种方式订阅float 类型的x和y,因此当我在代码上执行#EMPHASIS LINE(在我硬编码特定类型的行中)时,我可以检查是否有人将值赋给x和/或Vector实例的y是我定义它的类型:
x = component(float)
所以我尝试了这个(一个组件(描述符)类):
class component(object):
def __init__(self, t, initval=None):
self.val = initval
self.type = t
def __get__(self, obj, objtype):
return self.val
def __set__(self, obj, val):
self.val = val
像描述符一样使用组件,但我无法设法解决该类型。我试图做一个数组来保存val和type,但后来不知道如何从装饰器__setattr__方法中获取它。
你能指出我正确的方向吗?
PS:希望你们理解我想要做的事情并帮助我。提前致谢
解决方案
好吧,使用@Diego 的答案(我将接受)和一些解决方法来满足我的个人需求,我设法做到了这一点:
装饰器(组件化)
def componentized(cls):
class wrappedClass(object):
def __init__(self, *args):
self.wrappedInstance = cls(*args)
def __getattr__(self, name):
#Checking if we only request for a single char named value
#and return the value using getattr() for the wrappedInstance instance
#If not, then we return a tuple getting every wrappedInstance attribute
if(len(name) == 1):
return getattr(self.wrappedInstance, name)
else:
return tuple(getattr(self.wrappedInstance, char) for char in name)
def __setattr__(self, attributeName, value):
try:
#We check if there is not an instance created on the wrappedClass __dict__
#Meaning we are initializing the class
if len(self.__dict__) == 0:
self.__dict__[attributeName] = value
elif isinstance(value, tuple): # We get a Tuple assign
self.__checkMultipleAssign(attributeName)
for char, val in zip(attributeName, value):
setattr(self.wrappedInstance, char, val)
else:
#We get a value assign to every component
self.__checkMultipleAssign(attributeName)
for char in attributeName:
setattr(self.wrappedInstance, char, value)
except Exception as e:
print(e)
def __checkMultipleAssign(self, attributeName):
#With this we avoid assigning multiple values to the same property like this
# instance.xx = (2,3) => Exception
for i in range(0,len(attributeName)):
for j in range(i+1,len(attributeName)):
if attributeName[i] == attributeName[j]:
raise Exception("Multiple component assignment not allowed")
return wrappedClass
组件(描述符类)
class component(object):
def __init__(self, t):
self.type = t #We store the type
self.value = None #We set an initial value to None
def __get__(self, obj, objtype):
return self.value #Return the value
def __set__(self, obj, value):
try:
#We check whether the type of the component is diferent to the assigned value type and raise an exeption
if self.type != type(value):
raise Exception("Type \"{}\" do not match \"{}\".\n\t--Assignation never happened".format(type(value), self.type))
except Exception as e:
print(e)
else:
#If the type match we set the value
self.value = value
(代码注释是不言自明的)
通过这个设计,我可以实现我想要的(如上所述)谢谢大家的帮助。