Python重写默认属性赋值

时间:2018-05-15 16:53:55

标签: python-3.x

对于我使用的特定框架,我需要将对象属性定义为特殊类,例如,而不是写这个:

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。

这可能吗?

2 个答案:

答案 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>