4
I’m giving a study in Python and for this I am building a class in Python 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 the  $this (which refers to the current instance of the object), because I want to apply the 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, that a given method returns the instance of the class itself, but not the same instance, but a new one.
In python I have this currently:
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?
yes -
self.__class__ortype(self)- the two do the same thing. In Python 3, you can also use the magic variable__class__within a method (without theself) :__class__Only will always point to the class itself in which the method is defined - even ifselfis an instance of a sub-class of the same. That__class__magic (why it appears out of nowhere) is part of the mechanism used in Python 3 so thatsuperwork without parameters.– jsbueno
Just one question @jsbueno: If I use
__future__, can do this in Python 2 without the self?– Wallace Maxters
No -this feature was not ported retroactively to Python2. But so far, why are you using Python2 in 2016 anyway? (Until 2015 I would understand).
– jsbueno
@jsbueno seriously? now we can go to the
Python 3? Is that in my Ubuntu, by default is installed the2.7– Wallace Maxters
It’s been years on Ubuntu - many years - that you can have Python2 and 3 parallels - just instill with apt-get install python3. Ai, for each project, you install the separadametne requirements using virtualenv and Pip (do not use system packages) <- this practice is also recommended for proejtos in Python2.
– jsbueno
The question is more or less subjective, love until 2014, many of Python’s most important libraries and frameorks did not work in Python3 yet -or did not work properly. Today, silverily no important project that is basis for development (other than app for end user) is stuck only on Python2
– jsbueno