我正在学习如何用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
提前谢谢你。
发布于 2020-05-30 09:51:51
您可以使用@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
https://stackoverflow.com/questions/62092884
复制相似问题