【问题标题】:nested classes - how to use function from parent class?嵌套类 - 如何使用父类中的函数?
【发布时间】:2017-08-11 14:28:57
【问题描述】:

如果我有这种情况:

class Foo(object):
    def __init__(self):
        self.bar = Bar()

    def do_something(self):
        print 'doing something'

    class Bar(object):
        def __init(self):
            self.a = 'a'

        def some_function(self):

我想在 some_function 函数中调用 do_something 函数,但是这个函数不属于这个类,我该怎么做才能调用这个函数? 我不想将它与 Foo().do_something 一起使用,还有另一种选择吗? 我不想创建新实例

另一个例子:

class A(object):
    def __init__(self):
        self.content = 'abcdabcabcabc'
        self.b = self.B()
        self.c = self.C()    

    def some_function(self):
        print self.content

    class B(object):
        def foo(self):
            A.some_function()

    class C(object):
        def foo(self):
            A.some_function()

【问题讨论】:

标签: python python-2.7 class oop inner-classes


【解决方案1】:

Python 中的嵌套类没有实际用例,但可以用命名空间限定某些类属性。在这种情况下,您根本不应该创建它们的实例。

如果你有嵌套类的实例,你得到的只是一个令人头疼的问题——没有好处。 “Outter”类不会将它们视为任何特殊的东西——这与 C++ 中的不同,它看起来像这种模式的起源,嵌套类在整体上是容器类私有的。

在 Python 中私有的概念纯粹是按照惯例完成的,如果除了 Foo 之外没有其他代码应该使用 Bar 的实例,请在文档中将其称为 _Bar

除了嵌套不会帮助Bar 通过名称以外的任何其他方式获得对Foo 的引用(好吧,有使用描述符协议的方法,但不是为此) - 他们,如果你想在没有Foo 实例的情况下运行 Foo.do_something,do_something 无论如何都应该是一个类方法。

现在,如果您想要聚合 对象,那是另一回事。你要做的是:

class Bar(object):
    def __init(self, parent):
        self.parent = parent
        self.a = 'a'

    def some_function(self):
        self.parent.do_something(...)

class Foo(object):
    def __init__(self):
        self.bar = Bar(self)

    def do_something(self):
        print 'doing something'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多