嵌套类的范围? [英] Nested classes' scope?

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

问题描述

我试图了解Python嵌套类中的作用域.这是我的示例代码:

I'm trying to understand scope in nested classes in Python. Here is my example code:

class OuterClass:
    outer_var = 1
    class InnerClass:
        inner_var = outer_var

类的创建未完成,并且出现错误:

The creation of class does not complete and I get the error:

<type 'exceptions.NameError'>: name 'outer_var' is not defined

尝试inner_var = Outerclass.outer_var不起作用. 我得到:

Trying inner_var = Outerclass.outer_var doesn't work. I get:

<type 'exceptions.NameError'>: name 'OuterClass' is not defined

我正在尝试从InnerClass访问静态outer_var.

I am trying to access the static outer_var from InnerClass.

有没有办法做到这一点?

Is there a way to do this?

推荐答案

class Outer(object):
    outer_var = 1

    class Inner(object):
        @property
        def inner_var(self):
            return Outer.outer_var

这与其他语言中的类似功能不太相同,并且使用全局查找而不是限制对outer_var的访问. (如果更改名称Outer绑定到的对象,则此代码将在下次执行该对象时使用该对象.)

This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to outer_var. (If you change what object the name Outer is bound to, then this code will use that object the next time it is executed.)

如果您想让所有Inner对象都引用Outer,因为outer_var实际上是实例属性:

If you instead want all Inner objects to have a reference to an Outer because outer_var is really an instance attribute:

class Outer(object):
    def __init__(self):
        self.outer_var = 1

    def get_inner(self):
        return self.Inner(self)
        # "self.Inner" is because Inner is a class attribute of this class
        # "Outer.Inner" would also work, or move Inner to global scope
        # and then just use "Inner"

    class Inner(object):
        def __init__(self, outer):
            self.outer = outer

        @property
        def inner_var(self):
            return self.outer.outer_var

请注意,嵌套类在Python中并不常见,并且不会自动暗示类之间的任何特殊关系.您最好不要嵌套. (如果需要,您仍然可以在Outer上将class属性设置为Inner.)

Note that nesting classes is somewhat uncommon in Python, and doesn't automatically imply any sort of special relationship between the classes. You're better off not nesting. (You can still set a class attribute on Outer to Inner, if you want.)

这篇关于嵌套类的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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