I am giving a study in Python
and for this I am putting together a Python class that I had already done in PHP.
For example, in a given method in PHP
I needed to return the same instance of the class dynamically, but without using $this
(which refers to the current instance of the object), since I want to apply immutability in this case .
Example:
class Time {
public function diff(Time $time) {
$seconds = abs($time->getSeconds() - $this->getSeconds());
return new static(0, 0, $seconds);
}
}
That is, a given method returns the instance of the class itself, but not the same instance, but a new instance.
In python I currently have this:
class Time(object):
__seconds = 0
def __init__(self, **kw):
self.set_time(**kw)
def set_time(self, **kw):
seconds = (kw.get('hours', 0) * 3600) \
+ (kw.get('minutes', 0) * 60) \
+ kw.get('seconds', 0)
self.__seconds = seconds
return self
def diff(self, other):
seconds = abs(self.get_seconds() - other.get_seconds())
#como posso fazer para retornar uma nova instância com 'seconds' aqui?