1

I am trying to use a code that has been run successfully before by my colleagues.

But, when I try to replicate the situation I get an error. Here is the situation:

Class and function defined as:

Class X:

   def f1(self, params)
   ...

   def f2(self, params)
   ...

Class Y(X):

   def f3(self, params..)

   ...

   def G(self, params):

   ... so on

All of these are saved under 'classes.py' file in the notebook.

So, from my jupyter notebook, I am trying to call the function G() as:

import classes

X.G(params)

Now I get an error like:

" name 'X' is not defined "

I also tried calling like: Y.G(params) And get the similar error like name Y is not defined. I believe, there is no error on the code, as it has been run before.

Can anyone explain what could possibly go wrong here. Also, I do not understand the line definition of Class Y(X). My assumption, is Class Y is a sub class of main class X. But, anyway, some insights are helpful. Thank you

stackword_0
  • 185
  • 8

2 Answers2

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.

ThunderHorn
  • 1,975
  • 1
  • 20
  • 42
JLeno46
  • 1,186
  • 2
  • 14
  • 29
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.

MattDMo
  • 100,794
  • 21
  • 241
  • 231