向实例添加属性

时间:2018-07-29 18:20:10

标签: python-3.x

我有以下代码...

import math
class Circle:
    """Class to create Circle objects"""

    def __init__(self, radius=1):
        """Circle initializer"""
        self.radius = radius

    @property
    def area(self):
        """Calculate and return the area of the Circle"""
        return math.pi * self.radius ** 2

    @property
    def diameter(self):
        """Calculate and return the diameter of the Circle"""
        return self.radius * 2

    @diameter.setter
    def diameter(self, diameter):
        """Set the diameter"""
        self.radius = diameter / 2

    def __str__(self):
        return 'Circle of radius {}'.format(self.radius)

    def __repr__(self):
        return "Circle(radius={})".format(self.radius)

我想向实例添加属性radius_log。它是一个列表,其中将包含属于该圆的半径值以及当前半径值作为列表中的最后一项。其他属性必须仍然有效。我知道我必须将半径设置为属性,并为半径添加一个setter属性。下面是示例输出...

 circle = Circle()
    circle
Circle(radius=1)
    circle.radius_log
[1]
    circle.radius = 2
    circle.diameter = 3
    circle
Circle(radius=1.5)
    circle.radius_log
[1, 2, 1.5]
    circle2 = Circle(radius=2)
    circle2.radius_log
[2]

关于如何执行此操作的任何想法?

1 个答案:

答案 0 :(得分:1)

radius更改为属性,然后添加新属性radius_log

radius属性设置器中,您将在每次更改中将值添加到_property_log列表中。该日志将通过radius_log属性公开:

import math
class Circle:
    """Class to create Circle objects"""

    def __init__(self, radius=1):
        """Circle initializer"""
        self.radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        self._radius = getattr(self, '_radius', None)
        if self._radius == value:
            return
        self._radius_log = getattr(self, '_radius_log', [])
        self._radius_log.append(value)
        self._radius = value

    @property
    def radius_log(self):
        return self._radius_log[:]

    @property
    def area(self):
        """Calculate and return the area of the Circle"""
        return math.pi * self.radius ** 2

    @property
    def diameter(self):
        """Calculate and return the diameter of the Circle"""
        return self.radius * 2

    @diameter.setter
    def diameter(self, diameter):
        """Set the diameter"""
        self.radius = diameter / 2

    def __str__(self):
        return 'Circle of radius {}'.format(self.radius)

    def __repr__(self):
        return "Circle(radius={})".format(self.radius)

circle = Circle()
print(circle)
print(circle.radius_log)   
circle.radius = 2
circle.diameter = 3
print(circle)
print(circle.radius_log)    
circle2 = Circle(radius=2)
print(circle2.radius_log)

此打印:

Circle of radius 1
[1]
Circle of radius 1.5
[1, 2, 1.5]
[2]