简体   繁体   English

如何从Python的派生类中获取父类实例的名称?

[英]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. 现在,我想将“ f”附加(关联)到“ b”,这样,如果我将Bar实例化为b,它还应该存储父类的哪个实例正在调用派生类的实例。

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. 一种实现方法是将父类(Foo)实例“ f”解析为类(Bar)的“ _ init _ ”方法的参数。但是,这有点可笑。

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. 请记住,每个类可能都有大量实例,因此它无法自动知道哪个类应该与之“相关”-并使用各种魔术(例如检查父堆栈框架中是否包含Foo实例的变量)并希望这是唯一的一个),如果我是你的老板,这将是一个非常丑陋的理由,也是一个让你难对付的理由。

So, you should pass f as an argument to Bar() . 因此,您应该f作为参数传递给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. 如果您不想使用单独的Foo实例(即,您想要正常继承),则无需创建Foo实例,只需调用Foo.__init__(self, 'Hello')super(Bar, self).__init__('Hello')Bar构造函数中,并且可能接受该值作为参数,而不是对其进行硬编码。

It sounds like you may be confused about how inheritance works in Python. 听起来您可能对继承在Python中的工作方式感到困惑。 In the code you showed, f and b are not related, except by being instantiated right next to each other. 在您显示的代码中, fb没有关系,只是彼此相邻实例化了。

However, your Bar instance b does have access to a Foo instance, namely itself. 但是,您的Bar实例b确实有权访问Foo实例,即本身。 By declaring that Bar is a subclass of Foo you are saying that every instance of Bar is also an instance of Foo . 通过声明BarFoo的子类,您是说Bar每个实例也是Foo的实例。 You can test this, with isinstance(b, Foo) . 您可以使用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. 如果您需要从bar方法访问Foo定义的变量或方法,通常您可以直接在传递的self值上直接访问它。 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 : 或者,如果您要覆盖Bar的方法(即,定义一个与Foo中已经存在的方法同名的方法,则可以使用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.) (请注意,上面的代码是针对Python 3的。有一些小事情会使它在Python 2中无法正常工作。如果您出于维护除旧Python 2应用程序之外的其他原因学习Python,建议您学习Python 3 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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