Python inheritance and scoping question
Edited because I'm a moron. Should have said class originally.
I have the code that does something like this:
file1.py
class A(object):
def __init__(self):
stuff_here()
class B(object):
def func(self):
self.a = A()
file2.py
import file1
class A(file1.A):
def __init__(self):
file1.A(self)
self.thing = other_thing
class B(file1.B):
pass
开发者_如何学Go
I would like that when I instantiate file2.B() it uses file2.A() for its member a, not file1.A()
Is there a way to do this? I tried looking at the python scoping rules but I'm misunderstanding it I think.
You could use a class attribute to hold the class you would like to use. In the first file, use
class B(object):
A = A
def func(self):
self.a = self.A()
and in the second file, use
class B(file1.B):
A = A
Probably there is a better way of achieving whatever you want to achieve...
Edit: Your comment to your question suggests that you don't want to actually change the code in the first file. In this case, you could try to "monkey patch" file1.py
. Write file2.py
as
import file1
class A(file1.A):
def __init__(self):
file1.A(self)
self.thing = other_thing
file1.A = A
Now you actually substituted file1.A
by your own version. This is certainly hacky, but sometimes the quickest way to get somewhere.
Define a method in the parent that returns the class to use, and override it in the child.
精彩评论