Python - error in calling a function from a class

974 views Asked by At

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

2

There are 2 answers

1
JLeno46 On
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.

0
MattDMo On

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.