Python类中的命名空间 [英] Namespaces within a Python Class

查看:79
本文介绍了Python类中的命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        print i                     # self.i will work just fine
        return 'hello world'

当我这样做时:

>>> x = MyClass()
>>> 
>>> x.f()

我得到一个错误,如预期的那样.

I get an error, as expected.

我的问题是:

  1. 为什么会出现错误?

  1. Why do I get the error?

为什么在函数(或方法)定义的名称空间与包含该类的模块的全局名称空间之间没有名称空间?

Why is there no namespace between the namespace of the function(or method) definition and the global namespace of the module containing the class?

在这种情况下,除了使用self之外,还有其他方法可以引用i吗?

Is there any other way to reference i inside f in this case other than using self?

推荐答案

  1. 您遇到了错误,因为print i试图打印全局(对于模块)变量i.如果要使用该类的成员,则应编写self.i.
  2. 因为Guido Van Rossum决定不使用名称空间.实际上,我不知道该如何回答了.
  3. 是,但不是.是的,因为您可以使用反射"(我不记得在python中如何调用它)并访问该类的任何成员.不,因为使用self是唯一可用的方法.
  1. You've got an error because print i is trying to print a global (for the module) variable i. If you want to use the member of the class you should write self.i.
  2. Because Guido Van Rossum decided not to use namespaces. Actually, I don't know how to answer anymore.
  3. Yes, but no. Yes, because you can use "reflection" (I can't remember how it is called in python) and access any member of the class. No, because using self is the only usable way.

这篇关于Python类中的命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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