Even if you use it for more than 5 years, it is a candy ball for Python beginners
So, there is such a description in a book
class SomeClass(object):
..
I wondered what this "object" is, so make a note.
Python class inherits object(Stack Overflow)
In Python2 series, there are two types of classes, and if you are not newer, you will get a lot of information about types. Since there is only a new person in Python3, it seems to be one of the dying knowledge.
Well I will try it. There is also love that you can see from the results
class_exp.py
class OldClass:
def a(self):
print("I'm OldClass")
class OldChild(OldClass):
def a(self):
super(OldChild, self).a()
class NewClass(object):
def a(self):
print("I'm NewClass")
class NewChild(NewClass):
def a(self):
super(NewChild, self).a()
x = OldChild()
y = NewChild()
print(type(x))
print(type(y))
print('--')
try:
# Will fail with Python 2.x
x.a()
except TypeError as e:
import traceback
traceback.print_exc()
print('--')
y.a()
> python2.7 misc/class_exp.py
<type 'instance'>
<class '__main__.NewChild'>
--
Traceback (most recent call last):
File "misc/class_exp.py", line 27, in <module>
x.a()
File "misc/class_exp.py", line 10, in a
super(OldChild, self).a()
TypeError: must be type, not classobj
--
I'm NewClass
> python3.2 misc/class_exp.py
<class '__main__.OldChild'>
<class '__main__.NewChild'>
--
I'm OldClass
--
I'm NewClass
In Python2, the objects in the older class don't look as the type expected. There seems to be one point in the point that the result of type (obj) is `` <type'instance'>''. That's the relationship, I can't see the parent class correctly with super ().
Then read the old documentation.
(2 PEPs 252 and 253: Type and Class Changes)[http://docs.python.org/release/2.2.3/whatsnew/sect-rellinks.html]
By the way, the book at the beginning is a book that mainly focuses on Python3, so I'm not sure why I explicitly specified objects that are not needed in Python3.
Recommended Posts