Namespaces within a Python Class

纵饮孤独 提交于 2020-01-02 18:38:41

问题


I have this:

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

When I do:

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

I get an error, as expected.

My question is:

  1. Why do I get the error?

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

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


回答1:


  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.


来源:https://stackoverflow.com/questions/14299013/namespaces-within-a-python-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!