简体   繁体   English

从超类对象初始化子类实例

[英]Initializing a Subclass Instance from a Superclass Object

The documentation for logging.Logger states: logging.Logger的文档指出:

Note that Loggers are never instantiated directly, but always through the module-level function logging.getLogger(name) 请注意,永远不会直接实例化Logger,而是始终通过模块级函数logging.getLogger(name)实例化。

This leads me to the following question (for which I'll switch to some Foo class instead of logging.Logger , since I'd like to ask about the principle in general). 这引出了以下问题(由于我想一般地询问该原理,因此我将切换到一些Foo类而不是logging.Logger )。


Suppose there's some class Foo , with several attributes and methods: 假设有一些Foo类,具有几个属性和方法:

class Foo:
    def method_0(self..):
        ...

    def method_1(self..):
        ...

    def method_n(self..):
        ...

I'd like to subclass Foo , and specialize only a couple of these methods. 我想对Foo进行子类化,并且仅专门研究其中的几种方法。

class SubFoo(Foo):
    def method_1(self, ...):
        ...
        # Or super - not the point of the question.
        Foo.method_1(self, ...)

    ...

The problem is that Foo doesn't have a constructor available, only the means to create an object of type Foo , say via getFoo . 问题在于Foo没有可用的构造函数,而只有通过getFoo来创建Foo类型的对象的getFoo The " Foo " part of SubFoo needs to be an "approved" Foo object, and I don't know how to force SubFoo s Foo part to be made the "approved" object. SubFoo的“ Foo ”部分需要是“批准的” Foo对象,并且我不知道如何强制将SubFooFoo部件设置为“批准的”对象。

Note 注意

There are obviously several workarounds to subclassing Foo , eg, composition, monkey-patching, clever games with __dict__ / gettatr , etc. Notwithstanding, this question is about subclassing. 显然,有几种解决方法可以将Foo子类化,例如,构图,猴子补丁,使用__dict__ / gettatr聪明游戏等。尽管如此,这个问题还是关于子类化的。

You have misunderstood inheritance. 您对继承有误解。 To create an instance of SubFoo, you just have to instantiate it like you would any other class: SubFoo() . 要创建SubFoo的实例,只需像实例任何其他类一样将其实例化即可: SubFoo()

Python doesn't have constructors, and in any case a method not defined on a subclass will automatically inherit the superclass version without you needing to do anything. Python没有构造函数,在任何情况下,未在子类上定义的方法将自动继承超类版本,而无需执行任何操作。

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

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