从包中的单独文件中的类创建对象

时间:2017-02-23 14:28:29

标签: python

如何在python包中正确使用父子类? (init文件为空)

├── modula
│   │   ├── child.py
│   │   ├── __init__.py
│   │   ├── parent.py
│   │   └── __pycache__
│   │       ├── child.cpython-35.pyc
│   │       ├── __init__.cpython-35.pyc
│   │       └── parent.cpython-35.pyc
└───└── modulae.py

--- --- parent.py

class parent(object):
    def __init__(self):
        print('initialised parent')

---- --- child.py

import parent
class child(parent.parent):
    def __init__(self):
        print("initialised child")

--- --- modulae.py

import modula
modula.child()

错误说:

modulae.py", line 5, in <module>
    modula.child()
AttributeError: module 'modula' has no attribute 'child'

2 个答案:

答案 0 :(得分:0)

child.py应该有from . import parent,而modulae.py应该有from modula.child import childfrom modula import child; child.child()

答案 1 :(得分:0)

默认情况下,Python不会为您导入子包。所以如果你有:

modula
    __init__.py
    child.py

您无法通过以下方式访问儿童:

import modula
modula.child  # fails

因为您只告诉Python导入modula,而不是modula.child。你可以通过多种方式解决这个问题。

1。在child中导入modula.__init__.py

# __init__.py
# use a relative import because we're importing from the same package,
# otherwise this could be ambiguous (and doesn't work at all in 
# Python 3).
from . import child

# Now in my script I can do:
import modula
modula.child

2。在脚本中导入child(如果您不想在加载child时始终加载modula,则可能需要这样做:

# Script
import modula.child
modula.child  # works