从另一个模块调用父类方法时的NameError

问题描述 投票:0回答:2

在这里,我创建了两个名为test1.py和test2.py的python模块。

在test1.py中:

class c1: 
    pass

class c2:
    def e(self):
        return c3.x

在test2.py中:

from test1 import *

class c3(c1):
    x = 1
    def __init__(self,x):
        self.x = x

class c4(c2):
    def __init__(self,y):
        self.y = y

现在,我需要使用python 3.x解释器调用这些模块:

$ python
>>> import test2 as t2
>>> import test1 as t1
>>> a = t2.c4(2)
>>> b = t2.c3(4)
>>> a.e()
Traceback (most recent call last):
   File "<stdin>", line1, in <module>
   File "~/test.py", line 6, in e return c3.x
NameError: name 'c3' is not defined

有什么方法可以解决这个问题吗?

注意:如果我将它们放在单个模块test.py中:

class c1:
    pass

class c2:
    def e(self):
        return c3.x

class c3(c1):
    x = 1
    def __init__(self,x):
        self.x = x

class c4(c2):
     def __init__(self,y):
         self.y = y

如果我在解释器中运行它:

$ python
>>> from test import *
>>> a = c4(2)
>>> b = c3(4)
>>> a.e()
1

解决方案:是的!最后,这对我也有用。

我喜欢这样:

在test1.py中:

import test2

class c1:
    pass

class c2:
    def e(self):
        return test2.c3.x

在test2.py中:

from test1 import *

class c3(c1):
    x=1
    def __init__(self,x):
        self.x = x

class c4(c2):
     def __init__(self,y):
          self.y = y

如果我在Python 3.x解释器中运行它。我需要这样做:

$ python
>>> from test2 import *
>>> from test1 import *
>>> a = c4(2)
>>> b = c3(4)
>>> a.e()
1

警告:不要这样做:

$ python
>>> from test1 import *
Traceback (most recent call last):
...
NameError: name 'c1' is not defined
python inheritance import
2个回答
0
投票

test1不知道c3是什么。所以,你必须在test2进口test1。这可以在您的代码中引入循环依赖。您可以从以下链接中阅读有关python中循环依赖的更多信息:

Circular (or cyclic) imports in Python

Circular dependency in Python

https://gist.github.com/datagrok/40bf84d5870c41a77dc6

https://micropyramid.com/blog/understand-self-and-init-method-in-python-class/

这对我有用。

import test2 class c1: pass class c2: def e(self): a=test2.c3(4) print a.temp

import test1 class c3(test1.c1): def __init__(self,x): self.temp=x class c4(test1.c2): def __init__(self,y): self.y = y


0
投票

c2不知道c3是什么,因为它在另一个.py文件中。所以,你可能需要在test2中导入test1。这导致循环进口 - test1进口test2test2进口test1

要修复循环导入,要么重构程序以避免循环导入,要么将导入移动到模块的末尾(就像你做的第二种方式)。

© www.soinside.com 2019 - 2024. All rights reserved.