【发布时间】: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