1

我正在尝试使用我的同事之前已经成功运行过的代码。

但是,当我尝试复制这种情况时,我得到了一个错误。情况如下:

类和函数定义为:

Class X:

   def f1(self, params)
   ...

   def f2(self, params)
   ...

Class Y(X):

   def f3(self, params..)

   ...

   def G(self, params):

   ... so on

所有这些都保存在笔记本的“classes.py”文件下。

因此,从我的 jupyter 笔记本中,我尝试将函数 G() 称为:

import classes

X.G(params)

现在我收到如下错误:

" name 'X' is not defined "

我也尝试过这样的调用:Y.G(params) 并得到类似的错误,例如未定义名称 Y。我相信,代码没有错误,因为它之前已经运行过。

谁能解释这里可能出现的问题。另外,我不明白Class Y(X). 我的假设是,Y 类是主要 X 类的子类。但是,无论如何,一些见解是有帮助的。谢谢

4

2 回答 2

2
class X:
    def print_a(self):
        print('a')

    def print_b(self):
        print('b')

class Y(X):
    def print_a(self):
        print('overriden print a from class X')

instance = Y()
instance.print_a()

returns

overriden print a from class X

When you inherit a class in another class you coul use a functionalty from the inherited class, add aditional functionalities, or even override functionalities.

EDIT: Since you import classes your statement should look like

import classes
instance = classes.Y() #You should call a method from an instance of the class:
instance.G() #and the call the method:

Python class inheritance.

于 2020-10-04T21:30:13.467 回答
0

You are getting name X is not defined errors because X has not been defined. It would be available if you used from classes import X or accessed it as classes.X(). Also, you typically want to name an instantiation of a class

foo = classes.X()

for example.

于 2020-10-04T21:32:15.720 回答