[Tutor] __init__
Steven D'Aprano
steve at pearwood.info
Tue Sep 6 03:04:44 EDT 2016
On Mon, Sep 05, 2016 at 12:24:50PM +0000, Albert-Jan Roskam wrote:
> =====> Aha, thank you, I did not know that. So for Python-3-only code,
> the idiom is "class SomeClass:", and for Python2/3 code "class
> SomeClass(object)".
I prefer to explicitly inherit from object regardless of which version I
am using.
> What are the most common code changes a developer
> needs to make when switching from old- to new-style classes?
Apart from making sure you explicitly inherit from object in Python 2
(and optionally the same in 3), there aren't that many.
- use super() instead of manually calling the superclass method.
# Old way
class Parent:
...
class Child(Parent):
def method(self, arg):
result = Parent.method(self, arg)
process(result)
return result
# New way
class Parent(object):
...
class Child(Parent):
def method(self, arg):
result = super(Child, self).method(self, arg)
# in Python 3, write super().method(arg)
process(result)
return result
Other than that, I don't think there are any *common* changes. There are
new features which don't work in old-style classes, like property, but
everything else is mostly the same.
--
Steve
More information about the Tutor
mailing list