嵌套的Python类需要访问封闭类中的变量 [英] Nested Python class needs to access variable in enclosing class

查看:91
本文介绍了嵌套的Python类需要访问封闭类中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些解决方案",但是每次的解决方案似乎都是不要使用嵌套类,在外部定义类,然后再正常使用它们".我不喜欢这个答案,因为它忽略了我选择嵌套类的主要原因,即拥有一个常量池(与基类相关联),该常量池可用于所创建的所有子类实例.

I've seen a few "solutions" to this, but the solution every time seems to be "Don't use nested classes, define the classes outside and then use them normally". I don't like that answer, because it ignores the primary reason I chose nested classes, which is, to have a pool of constants (associated with the base class) accessible to all sub-class instances which are created.

这是示例代码:

class ParentClass:

    constant_pool = []
    children = []

    def __init__(self, stream):
        self.constant_pool = ConstantPool(stream)
        child_count = stream.read_ui16()
        for i in range(0, child_count):
            children.append(ChildClass(stream))

    class ChildClass:

        name = None

        def __init__(self, stream):
            idx = stream.read_ui16()
            self.name = constant_pool[idx]

所有类都传递一个参数,这是一个自定义的位流类.我的目的是要找到一种解决方案,该解决方案不需要我仍然在ParentClass中时读取ChildClass的idx值.所有子类流的读取都应在子类中完成.

All classes are passed a single param, which is a custom bitstream class. My intention is to have a solution that does not require me to read the idx value for ChildClass while still in the ParentClass. All child-class stream reading should be done in the child class.

此示例过于简化.常量池并不是我需要用于所有子类的唯一变量. idx变量不是从流读取器读取的唯一内容.

This example is over simplified. The constant pool is not the only variable i need available to all subclasses. The idx variable is not the only thing read from the stream reader.

这在python中甚至可能吗?无法访问父母的信息吗?

Is this even possible in python? Is there no way to access the parent's information?

推荐答案

尽管我提出了有点光顾"的评论(公平地称呼它!),实际上还有一些方法可以实现您想要的:不同的继承途径.一对:

Despite my "bit patronizing" comment (fair play to call it that!), there are actually ways to achieve what you want: a different avenue of inheritance. A couple:

  1. 编写一个装饰器,该装饰器在声明一个类后立即进行内省,找到内部类,然后将外部类的属性复制到它们中.

  1. Write a decorator that introspects a class just after it's declared, finds inner classes, and copies attributes from the outer class into them.

对元类做同样的事情.

这是装饰器方法,因为它是最简单的方法:

Here's the decorator approach, since it's the most straightforward:

def matryoshka(cls):

    # get types of classes
    class classtypes:
        pass
    classtypes = (type, type(classtypes))

    # get names of all public names in outer class
    directory = [n for n in dir(cls) if not n.startswith("_")]

    # get names of all non-callable attributes of outer class
    attributes = [n for n in directory if not callable(getattr(cls, n))]

    # get names of all inner classes
    innerclasses = [n for n in directory if isinstance(getattr(cls, n), classtypes)]

    # copy attributes from outer to inner classes (don't overwrite)
    for c in innerclasses:
        c = getattr(cls, c)
        for a in attributes:
            if not hasattr(c, a):
                setattr(c, a, getattr(cls, a))

    return cls

以下是其用法的简单示例:

Here is a simple example of its use:

@matryoshka
class outer(object):

    answer = 42

    class inner(object):

        def __call__(self):
            print self.answer

outer.inner()()   # 42

但是,我不禁认为其他答案中提出的一些想法会更好地为您服务.

However, I can't help but think some of the ideas suggested in other answers would serve you better.

这篇关于嵌套的Python类需要访问封闭类中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆