简体   繁体   中英

Create object from class in separate file in package

How to correcrly use parent child class in python package? (init file is empty)

├── 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()

Error says:

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

child.py should have from . import parent from . import parent and modulae.py should have from modula.child import child or from modula import child; child.child() from modula import child; child.child()

Python doesn't import subpackages for you by default. So if you have:

modula
    __init__.py
    child.py

You cannot access child by doing:

import modula
modula.child  # fails

Because you only told Python to import modula , not modula.child . You can get around this in a number of ways.

1. Import child in 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. Import child in the script (you may want this if you don't want the overhead of always loading child when you load modula :

# Script
import modula.child
modula.child  # works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM