简体   繁体   English

我可以在python 3中为描述符定义add方法吗?

[英]Can I define an add method for a descriptor in python 3?

I referenced the python docs here to see how to create a class property in python that has controlled getter and setter methods. 我在这里引用了python文档,以了解如何在python中创建已控制getter和setter方法的类属性。 https://docs.python.org/3/howto/descriptor.html#id6 https://docs.python.org/3/howto/descriptor.html#id6

I created a descriptor property class with this code: 我使用以下代码创建了描述符属性类:

class PropNumberString(object):
    def __init__(self, initval=None, name='var_int'):
        self.val = initval
        self.name = name

    def __get__(self, obj, objtype):
        print("in getter")
        return self.val

    def __set__(self, obj, val):
        print("in setter")
        self.val = int(val)

    def __add__(self, val):
        print("adding")
        print("val to add: ", val)
        self.val = int(self.val) + int(val)
        return self

    def __radd__(self, val):
        return self.__add__(val)


class ConnectionTemplate(object):
    tid = PropNumberString(0, "ID")

I tried to define an add method as well, intending it always add an integer even if a string is provided. 我也尝试定义一个add方法,即使提供了一个字符串,它也总是要添加一个整数。 This doesn't work, it seems that "__get__" is called and then the add method of the integer returned is called instead of my add method. 这不起作用,似乎调用了“ __get__”,然后调用了返回的整数的add方法,而不是我的add方法。

Here is a test to demonstrate: 这是一个测试以证明:

my_template = ConnectionTemplate()

print("Getting value")
print(my_template.tid)

print("Updating value")
my_template.tid = 100

print("Doing add")
my_template.tid = my_template.tid + "1"

print(my_template.tid)
print("type: ", type(my_template.tid))

Output: 输出:

Getting value
in getter
0
Updating value
in setter
Doing add
in getter
Traceback (most recent call last):
  File "connection_template.py", line 53, in <module>
    my_template.tid = my_template.tid + "1"
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Is there a good solution for this? 有一个好的解决方案吗?

EDIT: This is what I ended up doing, which incorporates the answer provided by Alex Hall 编辑:这就是我最终要做的事,其中包含了Alex Hall提供的答案

class StrInt(int):
    def __add__(self, val):
        return StrInt(super().__add__(int(val)))
    __radd__ = __add__

class PropNumberString(object):
    def __init__(self, val=None, name='var_name'):
        self.val = StrInt(val)
        self.name = name

    def __get__(self, obj, objtype):
        return self.val

    def __set__(self, obj, val):
        self.val = StrInt(val)

class ConnectionTemplate(object):
    tid_field = "ID"

    def __init__(self, tid=0):
        self.tid = PropNumberString(tid, self.ansa_tid_field)

    def __getattribute__(self, key):
        # see https://docs.python.org/3/howto/descriptor.html#id5
        "Emulate type_getattro() in Objects/typeobject.c"
        attrib = object.__getattribute__(self, key)
        if hasattr(attrib, '__get__'):
            return attrib.__get__(None, self)
        return attrib

    def __setattr__(self, key, val):
        try:
            attrib = object.__getattribute__(self, key)
        except AttributeError:
            self.__dict__[key] = val
            return
        if hasattr(attrib, '__set__'):
            attrib.__set__(None, val)
            return
        self.__dict__[key] = val

note: My motivation for using a custom descriptor instead of the property decorator is that I want my properties to be able to contain custom metadata, ie key value for json dump. 注意:我使用自定义描述符而不是属性装饰器的动机是,我希望我的属性能够包含自定义元数据,即json转储的键值。

You shouldn't need to define a custom descriptor for this. 您无需为此定义自定义描述符。 You just need tid to return a class that adds the way you want. 您只需要tid返回一个添加所需方式的类即可。 It's probably best to do the conversion on setting rather than getting. 最好是在设置而不是获取时进行转换。 Here is an implementation: 这是一个实现:

class MyInt(int):
    def __add__(self, val):
        return MyInt(super().__add__(int(val)))

    __radd__ = __add__


class ConnectionTemplate(object):
    def __init__(self):
        self._tid = 0

    @property
    def tid(self):
        return self._tid

    @tid.setter
    def tid(self, val):
        self._tid = MyInt(val)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM