使用继承基类的类导入包

时间:2017-09-01 04:18:16

标签: python inheritance import

我有一个关于导入包含继承基类的类的包的问题。这是我的目录结构:

.
|-- cisco.py
|-- cisco.pyc
|-- __init__.py
|-- __init__.pyc
|-- objects.py
`-- objects.pyc

0 directories, 6 files
user@jumpbox:~/objects# 

我的父类位于objects.py:

class BasePlatform(object):
        def __init__(self,ip,hostname):
                self.ip = ip
                self.hostname = hostname

                print self.ip,self.hostname

        def hello(self):
                print 'hello world'

我的孩子班级在cisco.py中:

class CiscoPlatform(BasePlatform):
        def somefunc(self):
                print 'hello world'

在我的 init .py中,我有这个:

from . import objects 
from . import cisco

但是当我执行时,这就是我得到的错误:

user@jumpbox:~/objects# cd ..
user@jumpbox:~# python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import objects
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "objects/__init__.py", line 2, in <module>
    from . import cisco
  File "objects/cisco.py", line 1, in <module>
    class CiscoPlatform(BasePlatform):
NameError: name 'BasePlatform' is not defined
>>> 
有人请帮帮我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

from objects import BasePlatform
class CiscoPlatform(BasePlatform):
     def somefunc(self):
         print 'hello world'

您需要将BasePlatform类导入cisco.py