对于我使用的特定框架,我需要将对象属性定义为特殊类,例如,而不是写这个:
class A:
def __init__(self):
self.some_int = 2
我需要写:
class A:
def __init__(self):
self.some_int = SpecialIntWrapper(name = "some_int", value = 2)
我想以某种方式覆盖运算符/方法,以便键入第一个代码(self.some_int = 2)将在幕后使用属性名称和值调用SpecialIntWrapper。
这可能吗?
答案 0 :(得分:2)
基本上有两种方式 - 通过@property
装饰器(除非你想影响任意名称,否则更好)
class MyClass:
def __init__(self):
self.some_int = 2
# if you know the name of the property define it as a property - a getter
@property
def some_int(self):
return self._some_int
# and a setter
@some_int.setter
def some_int(self, value):
self._some_int = SpecialIntWrapper("some_int", value)
或重载__setattr__
魔术方法
class MyClass:
def __init__(self):
self.some_int = 2
def __setattr__(self, name, value):
# in general if you dont know the names of the properties
# beforehand you can somehow filter them here
if name == "some_int":
super().__setattr__(name, SpecialIntWrapper(name=name, value=value))
else:
# to use the setattr in a default way, just call it via super(Python 3)
super().__setattr__(name, value)
some_int
将初始化为SpecialIntWrapper
实例
>>>print(MyClass().some_int)
<__main__.SpecialIntWrapper object at 0x03721810>
答案 1 :(得分:0)
像这样的东西
class SpecialIntWrapper:
def __init__(self, name, value):
pass
class MyClass:
def __init__(self):
self.some_int = 3
def __setattr__(self, key, value):
if key == 'some_int':
self.__dict__[key] = SpecialIntWrapper(key, value)
else:
self.__dict__[key] = value
print(MyClass().some_int)
# >>> <__main__.SpecialIntWrapper object at 0x1076f1748>