gpt4 book ai didi

Python3/Classes/OOP/如何使用方法更改对象自身的值?

转载 作者:太空狗 更新时间:2023-10-30 02:49:12 25 4
gpt4 key购买 nike

我正在使用如何像计算机科学家一样思考来学习 python:学习 python 3。

我正在学习 OOP,并整理了一些代码来回答书中的一个问题,但我觉得我应该做些其他的事情。

有问题的代码是incremental(),其目标是增加对象的值。现在我的最终解决方案是使我的方法成为初始化方法的副本,并在此处添加时间。

这感觉很马虎:

class MyTime:

def __init__(self, hrs=0, mins=0, secs=0,):
""" Create a new MyTime object initialized to hrs, mins, secs.
The values of mins and secs may be outside the range 0-59,
but the resulting MyTime object will be normalized.
"""

# calculate total seconds to represent
totalsecs = hrs*3600 + mins*60 + secs
self.hours = totalsecs // 3600 # split in h, m, s
leftoversecs = totalsecs % 3600
self.minutes = leftoversecs // 60
self.seconds = leftoversecs % 60

def incerment(self,t):
# increase the time by t amount
totalsecs = self.hours * 3600 + self.minutes * 60 + self.seconds + t
self.hours = totalsecs // 3600 # split in h, m, s
leftoversecs = totalsecs % 3600
self.minutes = leftoversecs // 60
self.seconds = leftoversecs % 60


t1 = MyTime(5,5,5)
t2 = MyTime(10,10,10)
t3 = MyTime(12,12,12)

print('before:',t1)
t1.incerment(100)
print('after:',t1)

那怎么样呢?
有没有办法清理这个?

最佳答案

那种感觉好像你应该做点别的是因为小时分钟属性

您实际上并不需要将这些值存储为对象的属性,您只希望能够在需要时访问这些值。

调用如下:

>>> t1.hours
5

那么,让我们使用 property 重写您的示例:

class MyTime:
def __init__(self, hrs=0, mins=0, secs=0):
self.totalsecs = hrs*3600 + mins*60 + secs

@property
def hours(self):
return self.totalsecs // 3600

@property
def minutes(self):
return self._get_leftoversecs() // 60

@property
def seconds(self):
return self._get_leftoversecs() % 60

def _get_leftoversecs(self):
return self.totalsecs % 3600

def increment(self, t):
self.totalsecs += t

使用示例:

>>> t1 = MyTime(5,5,5)
>>> t1.hours
5
>>> t1.hours()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> t1.seconds
5
>>> t1.totalsecs
18305
>>> t1.increment(10)
>>> t1.seconds
15
>>> t1.totalsecs
18315

我不知道你是否注意到了,但是你实际上不再需要increment函数了:

>>> t1.totalsecs += 10
>>> t1.totalsecs
18325

我知道 property 一定比你正在做的要领先一点,但我认为它值得一个例子。

编辑:作为Lattyware注意到也没有必要将 totalsecs 设为属性。

引用他的评论:Python 属性的伟大之处在于,您不需要像在某些语言中那样将所有内容都转换为 getter 和 setter 以保持一致的接口(interface)。

仅当出于某种原因您想隐藏 MyTime 的内部实现(显然重新集成increment() 方法)。

关于Python3/Classes/OOP/如何使用方法更改对象自身的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9348034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com