1

I have problem in defining a getter by using @property in concrete class. Here is the python code:

from abc import ABCMeta, abstractproperty

class abstract(object):
    __metaclass__ = ABCMeta

    def __init__(self, value1):
        self.v1 = value1

    @abstractproperty
    def v1(self):
        pass

class concrete(abstract):
    def __init__(self, value1):
        super(concrete, self).__init__(value1)

    @property
    def v1(self):
        return self.v1

Then test the code and get this error:

test_concrete = concrete("test1")
test_concrete.v1

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-190-eb896d7ec1c9> in <module>()
----> 1 test_concrete = concrete("test1")
      2 test_concrete.v1

<ipython-input-189-bf15021022d3> in __init__(self, value1)
     11 class concrete(abstract):
     12     def __init__(self, value1):
---> 13         super(concrete, self).__init__(value1)
     14 
     15     @property

<ipython-input-189-bf15021022d3> in __init__(self, value1)
      3 
      4     def __init__(self, value1):
----> 5         self.v1 = value1
      6 
      7     @abstractproperty

AttributeError: can't set attribute

Basically I intend to set v1 as a read-only attribute.

I am used to using the same name for the attribute and its getter function, but it seems that I cannot do it if the class inherited from an abstract class.

I found a workaround by using different name for the getter function v1 as get_v1:

class abstract(object):
    __metaclass__ = ABCMeta

    def __init__(self, value1):
        self.v1 = value1

    @abstractproperty
    def get_v1(self):
        pass

class concrete(abstract):
    def __init__(self, value1):
        super(concrete, self).__init__(value1)

    @property
    def get_v1(self):
        return self.v1

Is there a better workaround for this problem?

4

1 回答 1

2

您的问题与抽象类无关。这是一个命名空间问题;属性对象和实例属性占用相同的命名空间,您不能同时让实例属性和属性使用完全相同的名称。

您正在尝试通过使用来访问该属性self.v1 = ...,并且v1不是神奇地是一个实例属性,只是因为您是从实例上的方法访问它,该方法始终是属性对象。

同样,您的属性 getter 将导致无限循环:

@property
def v1(self):
    return self.v1

因为self.v1 属性对象,而不是实例属性。

为实际存储使用不同的名称:

def __init__(self, value1):
    self._v1 = value1

@property
def v1(self):
    return self._v1

请注意,您不能在 Python 中拥有真正的私有属性(就像在 C# 或 Java 中一样);名称的前导下划线只是一个约定,确定的编码器始终可以直接访问您的实例状态。property对象不会改变这一点。

于 2015-08-12T10:02:59.340 回答