简体   繁体   中英

How to get the name of the instance of the parent class from the derived class in Python?

Hi i want to get the instance name of base class from the inherited child class.

for ex.

class Foo():
    def __init__(self, fakeArg):
        self.a = fakeArg

class Bar(Foo):
    def __init__(self, fakeArg1):
        Foo.__init__(self)
        self.b = fakeArg1
        # say, i store parent(Foo) instance in an variable too
        self.c = f

f = Foo('Hello')
b = Bar('Bar')

Now i want to attach(relate) "f" to "b", such that if i instantiate class Bar as b, it should also store which instance of parent class is calling the derived class instance.

one way to do it is to parse parent class(Foo) instance "f" as an argument to the " _ init _ " method of class(Bar).But, that is kind of a hack.

Kindly provide a solution to the problem.

Thanks in advance.

What sounds like a hack for you is how you should do it.

Remember that there might be tons of instances of each class so it cannot automatically know which one is supposed to be "related" to it - and using any kinds of magic (such as checking the parent stack frame for a variable holding an instance of Foo and hoping that's the only one) would be extremely ugly and a reason to slap you hard in the face if I were your boss.

So, you should pass f as an argument to Bar() .

In case you do not want a separate Foo instance - ie you want normal inheritance - there's no need to create an instance of Foo , simply call Foo.__init__(self, 'Hello') or super(Bar, self).__init__('Hello') in the Bar constructor and possibly accept the value as an argument instead of hardcoding it.

It sounds like you may be confused about how inheritance works in Python. In the code you showed, f and b are not related, except by being instantiated right next to each other.

However, your Bar instance b does have access to a Foo instance, namely itself. By declaring that Bar is a subclass of Foo you are saying that every instance of Bar is also an instance of Foo . You can test this, with isinstance(b, Foo) .

If you need to access a variable or method defined in Foo from a method of bar , usually you can just access it directly on the self value you get passed. Or if you're overriding a method in Bar (that is, defining a method with the same name as one that already exists in Foo you can use super :

class Foo:
    def __init__(self, a):
        self.a = a

    def sayHello(self):
        print("Hello!")

class Bar(Foo):
    def __init__(self, a, b):
        super().__init__(self, a)  # calls overridden __init__ method from Foo
        self.b = b

    def doSomething(self):
        self.sayHello()            # calls a method defined in Foo
        return self.a + self.b     # accesses variable "a" that was set in Foo

(Note that the code above is for Python 3. There are a few small things that will make it not work correctly in Python 2. If your learning Python for any reason other than maintaining a legacy Python 2 application, I suggest learning with Python 3.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM