编写函数来定义类属性

时间:2015-06-17 11:11:00

标签: python

我最近在Python中编写了一个非常基本的数据类的定义,我提出了以下内容:

class A:

    def __init__(self, **kwargs):
        self.__a1 = kwargs.get('some_value', -1)

    @property
    def a1(self):
        return self.__a1

    @a1.setter
    def a1(self, new_a1):
        self.__a1 = new_a1

它继续。在这种情况下,值-1可以替换为各种" null"值:-1""[]等,some_value来自我之前定义的Enum

因为类定义包含多个这些属性定义,并且它们都非常相同,所以我想编写一个函数来为我完成此操作。我很确定它在Python中是可行的,但我从来没有尝试过,所以我希望有一些指示。

1 个答案:

答案 0 :(得分:2)

假设您想简化重复属性定义,可以使用通用descriptor来显着简化:

class ProtectedAttribute(object):
    """Basic descriptor functionality for a protected attribute.

    Args:
      name (str): The name of the attribute to back the descriptor
        (usually the name the descriptor is assigned to with a single
        additional leading underscore).

    """

    def __init__(self, name, **kwargs):
        self.name = name

    def __get__(self, obj, typ):
        return getattr(obj, self.name)

    def __set__(self, obj, value):
        setattr(obj, self.name, value)

    def __delete__(self, obj):
        delattr(obj, self.name)

现在你可以这样做:

class A(object):

    a1 = ProtectedAttribute('__a1')

    def __init__(self, **kwargs):
        self.a1 = kwargs.get("some_value", -1)

还请注意使用dict.get来简化__init__

相关问题