class Foo(object):
def __init__(self):
self.list_one = [1, 2, 3]
class Bar(object):
def init(self):
self.list_two = Foo.list_one + [4, 5, 6] # I know this won't work unless I
# make list_one a class level variable
So, the question is – is there any way to merge those lists without instantiation of Foo or making list_one a class level variable?
Maybe there is a way of doing so using inheritance and super() but I can’t understand how do I access variables inside methods with it. I also would be very grateful for an answer how to do it without using inheritance.
It’s impossible to do the exact thing you describe.
selfis a reference to an instance ofFoo, and doesn’t exist until the class is instantiated; andlist_oneis an attribute ofself, assigned toselfafter it has already been created. Solist_onedoesn’t exist at all until after the class has been instantiated.To do what you’re asking using inheritance is fairly simple, however:
More generally, it’s not really meaningful to refer to “variables inside methods” except during the execution of the method or function, or when referring to what’s called the closure created by the function. Every time a function is called, a new namespace is created, and local variable names are created anew inside that namespace.
It is possible to refer to them once the function has been called, though. For example:
Observe that the two versions of
barrefer to different values ofa, each of which were created whenfoo(5)andfoo(6)were called.