【问题标题】:A class within a class, should this be fixed or is it intentional?一个类中的一个类,这应该是固定的还是故意的?
【发布时间】:2016-06-17 20:18:32
【问题描述】:

今天我正在试验和/或玩弄 Python 3.5。

我碰巧“不小心”这样写:

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() 之类的函数是如何创建的,还是使用另一个“方法”创建的?
这应该被修复,还是故意的?

提前谢谢你。

【问题讨论】:

  • 我不确定,但我认为 import os 会从 os.py... @ 必须是 path 类中的 function
  • os.path 是一个子模块os 是一个
  • 如果os.path 是一个类,那么您可以创建os.path 的实例,这没有任何意义,您的代码也存在同样的问题。执行x = Apple.red() ; x.eat() 会引发错误,因为eat 不是有效方法(缺少self 参数)

标签: python class python-3.x inner-classes python-3.5


【解决方案1】:

类中的类在 python 中工作得很好 -- 但是,python 处理命名空间的主要机制是 modulespackages,而不是类。我没有发现类中的类有很多用途(尽管可能有一些有效的用例)。

要设置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显然,这只是许多种设置方法之一。如果没有你在做什么的真实例子,很难给出任何具体的建议

【讨论】:

  • 感谢您的宝贵时间和帮助,非常感谢,+1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多