Issue
I'm struggling with understanding which methods are called when an old-style object is created.
Doing a little research I found that this differentiation only applies for python 2.7 not for python 3, however, I'm testing the methods in code:
class OldClass():
pass
class NewClass(object):
pass
old = OldClass()
new = NewClass()
print(type(old))
print(type(new))
print(old.__class__) #It retrieves __main__
print(old.__new__) #Never called
print(old.__init__) #Never called
And this the output:
<type 'instance'>
<class '__main__.NewClass'>
__main__.OldClass
Traceback (most recent call last):
File "main.py", line 29, in <module>
print(old.__init__)
AttributeError: OldClass instance has no attribute '__init__'
I'm continuing in research for this topic, here are some links with some information related:
New Style class vs Old style: https://www.youtube.com/watch?v=KwpnXqnVx2o
stack overflow new style vs old style class: What is the difference between old style and new style classes in Python?
If I find something I will update the post
Solution
__init__
only exists and is only called if you define it. Since you didn't define __init__
, it's not called. When it is defined, it's the only useful point of interception to creating the instance, and most of what you're trying to do works fine.
New-style classes can also use __new__
to hook instance construction (as opposed to initialization), and also allow for metaclasses (which can hook stuff in even crazier ways), but they're not available for old-style classes (defining __new__
doesn't change anything, and using metaclasses implicitly opts in to new-style classes).
Answered By - ShadowRanger
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.