嵌套类的范围?

我正在尝试了解Python中嵌套类的作用域。这是我的示例代码:


class OuterClass:

    outer_var = 1

    class InnerClass:

        inner_var = outer_var

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


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

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


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

我正在尝试从访问静态outer_var信息InnerClass。


有没有办法做到这一点?


互换的青春
浏览 431回答 3
3回答

qq_花开花谢_0

class Outer(object):&nbsp; &nbsp; outer_var = 1&nbsp; &nbsp; class Inner(object):&nbsp; &nbsp; &nbsp; &nbsp; @property&nbsp; &nbsp; &nbsp; &nbsp; def inner_var(self):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Outer.outer_var这与其他语言中的类似功能不太一样,并使用全局查找而不是限制对的访问outer_var。(如果更改名称Outer绑定到的对象,则此代码将在下次执行该对象时使用该对象。)相反,如果您希望所有Inner对象都具有对的引用,Outer因为outer_var它实际上是实例属性:class Outer(object):&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self.outer_var = 1&nbsp; &nbsp; def get_inner(self):&nbsp; &nbsp; &nbsp; &nbsp; return self.Inner(self)&nbsp; &nbsp; &nbsp; &nbsp; # "self.Inner" is because Inner is a class attribute of this class&nbsp; &nbsp; &nbsp; &nbsp; # "Outer.Inner" would also work, or move Inner to global scope&nbsp; &nbsp; &nbsp; &nbsp; # and then just use "Inner"&nbsp; &nbsp; class Inner(object):&nbsp; &nbsp; &nbsp; &nbsp; def __init__(self, outer):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.outer = outer&nbsp; &nbsp; &nbsp; &nbsp; @property&nbsp; &nbsp; &nbsp; &nbsp; def inner_var(self):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self.outer.outer_var请注意,嵌套类在Python中并不常见,并且不会自动暗示类之间的任何特殊关系。您最好不要嵌套。(您仍然可以设置一个类属性上Outer到Inner,如果你想要的。)

慕娘9325324

如果您不使用嵌套类,则可能会更好。如果必须嵌套,请尝试以下操作:x = 1class OuterClass:&nbsp; &nbsp; outer_var = x&nbsp; &nbsp; class InnerClass:&nbsp; &nbsp; &nbsp; &nbsp; inner_var = x或者在嵌套它们之前声明两个类:class OuterClass:&nbsp; &nbsp; outer_var = 1class InnerClass:&nbsp; &nbsp; inner_var = OuterClass.outer_varOuterClass.InnerClass = InnerClass(在此之后,您可以del InnerClass根据需要。)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python