class 中的 class,这是应该修复还是故意的?

A class within a class, should this be fixed or is it intentional?

今天我正在试验和/或摆弄 Python 3.5.

我刚好"accidentally"写了这个:

class Apple(object):
    class green(object):
        def eat():
            print("You just ate a green apple...")

    class red(object):
        def eat():
            print("You just ate a red apple...")

意思是我现在可以做:

Apple.red.eat() # would print: "You just are a red apple..."
Apple.green.eat() # would print: "You just are a green apple..."

这让我问,os.path.exists() 等函数是如何创建的,还是使用另一个 "method"?
创建的? 这是应该修复还是故意的?

提前致谢。

类 中的

类 在 python 中工作得很好——但是,python 处理命名空间的主要机制是 modules 软件包 ,而不是 类。我没有在 类 中找到 类 的大量用途(尽管可能有 一些 有效用例)。

要设置类似 os.path.exists 的东西,我会引导您到 source 除了 os.path 做了一些非常粗略的事情来设置它的命名空间(修改 sys.modules) 并避免使用包。你最好创建一个包,除非你需要有条件地以相同的名称导入不同的东西......

在这种情况下,要设置一个包,您可以使用类似于 1:

的目录结构
apples
  +--  __init__.py  (empty)
  |
  +--  base.py  (holds BaseApple class)
  |
  +--  green.py (holds GreenApple which inherits from BaseApple)
  |
  +--  red.py  (holds RedApple which inherits from BaseApple)

然后,假设您的 PYTHONPATH 可以正确找到所有内容,您会这样做:

from apples.green import GreenApple
from apples.red import RedApple

1显然,这只是 许多 设置方式之一。没有你在做什么的真实例子,很难给出任何具体的建议