Reputation: 29
On the path to enlightenment, I smoked many manuals :)
In the directory 'schemes' we have some files:
'scheme.py'
'scheme_New.py'
'scheme_New2.py'
...
In file 'scheme_New.py' (It's few code for unique case) we have code:
class Scheme:
def hi(self):
print('Hi from NEW')
In file 'scheme.py' (It's Main Scheme with a lot of code) we have code:
class Scheme:
def __new__(cls):
from schemes.scheme_New import Scheme as NewScheme
return type('Scheme', (NewScheme, cls), {})
def hi(self):
print('Hi from Base Scheme')
Then i try (any other file):
from schemes.scheme import Scheme
scheme = Scheme()
scheme.hi()
And I get the error:
TypeError: hi() missing 1 required positional argument: 'self'
Why self is not passed?
I want to override the base class 'Scheme' from a file 'scheme.py' with a class with the SAME (important) name from the file 'scheme_New.py' and return it.
Please explain to me why this happens? What am I doing wrong?
It can be done differently, but I want it that way.
I really want to figure this out!
I appreciate all your help.
Upvotes: 2
Views: 84
Reputation: 24077
I have no idea why you'd want something like this though, but if you insist on doing it like this, it can be done.
Your code was actually quite close. The reason why it doesn't work is that you just return the newly created class object and not an instance of the class, thus there never is an instance (=self
) to pass to the hi
method.
To fix the issue, you need to simply call object.__new__
with the created type as an argument:
schemes/scheme_New.py:
class Scheme:
def hi(self):
print('Hi from NEW')
schemes/scheme.py:
class Scheme:
def __new__(cls):
from schemes.scheme_New import Scheme as NewScheme
created = type('Scheme', (NewScheme, cls), {})
return object.__new__(created)
def hi(self):
print('Hi from Base Scheme')
main.py:
from schemes.scheme import Scheme
scheme = Scheme()
scheme.hi()
Output:
Hi from Base Scheme
Upvotes: 2