首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为Python类实例创建属性

为Python类实例创建属性
EN

Stack Overflow用户
提问于 2020-05-30 02:54:26
回答 1查看 25关注 0票数 0

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

代码语言:javascript
运行
复制
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

提前谢谢你。

EN

回答 1

Stack Overflow用户

发布于 2020-05-30 09:51:51

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

在您的示例中:

代码语言:javascript
运行
复制
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

输出:

代码语言:javascript
运行
复制
used_bandwidth: 2, total_bandwidth: 8
25.0
used_bandwidth: 4, total_bandwidth: 8
50.0
used_bandwidth: 4, total_bandwidth: 8
50.0
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62092884

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档