【问题标题】:Creating a property for Python Class instance为 Python 类实例创建属性
【发布时间】:2020-05-29 18:54:25
【问题描述】:

我正在学习如何用 Python 编写代码。 我创建了一个带宽类,它具有 _get_bandwidth 和 _set_bandwidth 私有方法。为使用的带宽创建了一个属性。不确定如何创建一个属性,当在带宽对象上调用该属性时,将给出已用带宽的百分比。请看下面的代码,谢谢。

class Bandwidth():
    def __init__(self, total_bandwidth, used_bandwidth = 0):
        self.total_bandwidth = total_bandwidth
        self._used_bandwidth = used_bandwidth

    #get used bandwidth    
    def _get_bandwidth(self):
        return self._used_bandwidth

    #set bandwidth
    def _set_bandwidth(self, bandwidth):
        if bandwidth < self.total_bandwidth:
            self._used_bandwidth = bandwidth

    bandwidth_used = property(_get_bandwidth, _set_bandwidth)


    # A percentage property that calculates how much bandwidth has been used
    # The percentage property should be read-only.

    #percentage = property()



lebara = Bandwidth(8)
lebara.bandwidth_used = 2
# print(lebara.percentage) # should give 0.25

# lebara.bandwidth_used = 4
# print(lebara.percentage) # should give 0.5

# lebara.bandwidth_used = 10 # _bandwidth used should not change because there's only 8 bits in a byte
# print(lebara.percentage) #  should give 0.5

提前谢谢你。

【问题讨论】:

标签: python-3.x function class


【解决方案1】:

您可以使用@property 装饰器来修改getter 的行为,并像访问属性一样访问它。同样,您可以使用@attribute.getter 装饰器来模仿直接设置属性值的行为:

在你的例子中:

class Bandwidth():
    def __init__(self, total_bandwidth, used_bandwidth=0):
        self._total_bandwidth = total_bandwidth
        self._used_bandwidth = used_bandwidth

    @property
    def used_bandwidth(self):
        return self._used_bandwidth

    @used_bandwidth.setter
    def used_bandwidth(self, bw):
        if 0 < bw <= self._total_bandwidth:
            self._used_bandwidth = bw

    @property
    def pcent_used(self):
        print(f'used_bandwidth: {self.used_bandwidth}, total_bandwidth: {self._total_bandwidth}')
        return (self.used_bandwidth / self._total_bandwidth) * 100  #<-- remove * 100 if you need a decimal between 0 and 1


lebara = Bandwidth(8)
lebara.used_bandwidth = 2
print(lebara.pcent_used) # should give 25

lebara.used_bandwidth = 4
print(lebara.pcent_used) # should give 50

lebara.used_bandwidth = 10
print(lebara.pcent_used) # should give 50   # remains unchanged

输出:

used_bandwidth: 2, total_bandwidth: 8
25.0
used_bandwidth: 4, total_bandwidth: 8
50.0
used_bandwidth: 4, total_bandwidth: 8
50.0

【讨论】:

猜你喜欢
  • 2016-01-09
  • 2010-12-10
  • 2011-11-24
  • 1970-01-01
  • 2013-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多