创建一个允许调整基值的Attribute类?

时间:2015-03-12 00:40:06

标签: python python-3.x get attributes set

我想创建一个Attribute类,所以我可以做类似的事情:

class Creature:
    def __init__(self, health=100, armor=0):
        self.health = Attribute(health)
        self.armor = Attribute(armor)

现在我做的时候

c1 = Creature()
c1.health += 10

它实际上并没有改变实际值,但它将health base 值保持为100,同时给它调整+10。

以下是我尝试过的内容,但它使用了healt.get()health.set(),这是不需要的:

class Attribute:
    def __init__(self, base=0, adjustments=None):
        self._base = base
        self._adjustments = adjustments or []

    def set(self, value):
        difference = value - self._base
        if difference:
            self._adjustments.append(difference)

    def get(self):
        return self._base + sum(self._adjustments)

c1 = Creature(50)
c1.health.set(60)  # Adds +10 adjustment

但我希望能够做到这一点:

c1 = Creature(50)
c1.health = 60
# Or just:
c1.health += 10

这可能吗?

2 个答案:

答案 0 :(得分:3)

以下是可能满足您需求的四种方法。


描述符

Descriptors允许您在隐藏底层实现时提供直接属性访问。

class AttributeDescriptor(object):
    def __init__(self):
        self.initialized = False
        self.base = 0
        self.adjustments = []

    def compute(self):
        return self.base + sum(self.adjustments)

    def __set__(self, inst, value):
        if not self.initialized:
            self.base = value
            self.initialized = True
            print("Attribute initialized to %s" % value)
        else:
            # Calculate delta
            delta = (value - self.compute())
            self.adjustments.append(delta)
            print("Adjustment added: %s" % delta)

    def __get__(self, inst, owner):
        return self.compute()

class Creature(object):
    health = AttributeDescriptor()
    armor  = AttributeDescriptor()

    def __init__(self, health=100, armor=0):
        self.health = health
        self.armor  = armor


c1 = Creature(50)
c1.health = 60      # Adds a +10 adjustment
print c1.health     # 60
c1.health += 10     # Add a +10 adjustment
print c1.health     # 70
#print c1.health.adjustments     # This won't work ('int' object has no attribute 'adjustments')

输出:

Attribute initialized to 50
Attribute initialized to 0
Adjustment added: 10
60
Adjustment added: 10
70

这种方法的问题在于您没有简单的方法来访问描述符的内部。因此,在这种情况下,您无法检查adjustments列表。但是,您可以直接将c1.health = X分配给它,就像它是普通属性一样。

注意:正如Veedrac在评论中所指出的,这些属性是在类级定义的,将在Creature类的所有实例之间共享。仅仅因为这个原因,它不是一个解决方案,但无论如何它都不是一个好的解决方案。

普通跟踪器对象

您可以使用实现“augmented assignment”魔法__iadd__()__isub__()

的类
class AttributeObject(object):
    def __init__(self, base):
        self.base = base
        self.adjustments = []
        print("Attribute initialized to %s" % base)

    def __compute(self):
        return self.base + sum(self.adjustments)

    def __int__(self):
        return self.__compute()

    def __iadd__(self, delta):
        print("Adjustment added: %s" % delta)
        self.adjustments.append(delta)
        return self

    def __isub__(self, delta):
        print("Adjustment added: %s" % -delta)
        self.adjustments.append(-delta)
        return self

class Creature(object):
    def __init__(self, health=100, armor=0):
        self.health = AttributeObject(health)
        self.armor =  AttributeObject(armor)


c1 = Creature(50)
#c1.health = 60         # Can't do this, because it will override the AttributeObject
print int(c1.health)    # 60
c1.health += 10         # Add a +10 adjustment
print int(c1.health)    # 70
print c1.health.adjustments  # [10]

输出:

Attribute initialized to 50
Attribute initialized to 0
50
Adjustment added: 10
60
[10]

此方法的问题在于,如果不覆盖属性,则无法直接分配属性。换句话说,c1.health = X会将health属性的值覆盖为等于X - 您将失去之前的任何内容。

但是通过这种方法,您可以访问adjustments列表:print c1.health.adjustments

请注意,c1.healthAdjustmentTracker的实例,而不是您可能期望的数字类型(尝试print c1.health)。您可以通过多种方式访问​​/提取数值,在我使用int(c1.health)类型转换的示例中(可能是因为我实现了__int__)。

描述符+跟踪器对象

使用上述两种方法的组合,您可以使用列出的所有语法。

class AttributeDescriptor(object):
    def __init__(self, attr):
        self.attr = attr

    def __set__(self, inst, value):
        getattr(inst, self.attr).update(value)

    def __get__(self, inst, owner):
        return getattr(inst, self.attr).compute()


class AdjustmentTracker(object):
    def __init__(self, base):
        print("Attribute initialized to %s" % base)
        self.base = base
        self.adjustments = []

    def compute(self):
        return self.base + sum(self.adjustments)

    def update(self, value):
        delta = (value - self.compute())
        print("Adjustment added: %s" % delta)
        self.adjustments.append(delta)


class Creature(object):
    health = AttributeDescriptor('_health')
    armor  = AttributeDescriptor('_armor')

    def __init__(self, health=100, armor=0):
        self._health = AdjustmentTracker(health)
        self._armor =  AdjustmentTracker(armor)


c1 = Creature(50)
c1.health = 60      # Adds a +10 adjustment
print c1.health     # 60
c1.health += 10     # Add a +10 adjustment
print c1.health     # 70
print c1._health.adjustments     # [10, 10]

输出:

Attribute initialized to 50
Attribute initialized to 0
Adjustment added: 10
60
Adjustment added: 10
70
[10, 10]

在这里,描述符不会跟踪基本和调整列表本身,而是将它们用作与AdjustmentTracker obejcts接口的代理。有了这个,您可以直接分配(例如c1.health = 60访问基础初始基础/调整(例如c1._health.adjustments)。

属性+跟踪器对象

与前面的示例一样,我们使用AdjustmentTracker个对象来保存属性的状态。但在此示例中,您可以使用properties来屏蔽属性,而不是使用显式描述符。

class AdjustmentTracker(object):
    def __init__(self, base):
        print("Attribute initialized to %s" % base)
        self.base = base
        self.adjustments = []

    def compute(self):
        return self.base + sum(self.adjustments)

    def update(self, value):
        delta = (value - self.compute())
        print("Adjustment added: %s" % delta)
        self.adjustments.append(delta)


class Creature(object):
    @property
    def health(self):         return self._health.compute()
    @health.setter
    def health(self, value):  self._health.update(value)

    @property
    def armor(self):          return self._armor.compute()
    @armor.setter
    def armor(self, value):   self._armor.update(value)

    def __init__(self, health=100, armor=0):
        self._health = AdjustmentTracker(health)
        self._armor =  AdjustmentTracker(armor)


c1 = Creature(50)
c1.health = 60      # Adds a +10 adjustment
print c1.health     # 60
c1.health += 10     # Add a +10 adjustment
print c1.health     # 70
print c1._health.adjustments     # [10, 10]

输出:

Attribute initialized to 50
Attribute initialized to 0
Adjustment added: 10
60
Adjustment added: 10
70
[10, 10]

此示例与前一个示例基本相同,因为它使用了属性,功能完全相同,所以只需更少的代码行。

答案 1 :(得分:1)

查看属性 https://docs.python.org/3/library/functions.html#property

在下面的示例中,属性被用作装饰器。

class Creature:
    def __init__(self, health):
        self._base_health = health
        self._modifications = []
    @property
    def health(self):
        return self._base_health + sum(self._modifications)
    @health.setter
    def health(self, value):
        self._modifications.append(value - self._base_health - sum(self._modifications))

每次检索健康属性时,都会调用getter函数(标有property装饰器的函数)。类似地,当设置了health属性时,将调用setter函数(标有health.setter装饰器的函数)。

c1 = Creature(50)
c1.health = 60
c1.health += 10
print(c1.health)
c1.health = 40
print(c1.health)

输出

70
40