1

When I try to do this I get the error NameError: global name 'name' is not defined is there an easy work around?

class C(object): 
 def __init__(self, name): 
 self.name = name
class D(C): 
 def __init__(self): 
 C.__init__(self, name)
obj1 = D() 
hongsy
1,5763 gold badges28 silver badges42 bronze badges
asked Jan 22, 2020 at 3:28
2
  • hi and welcome to SO! this looks like homework. please read asking about homework and edit your question if required. Commented Jan 22, 2020 at 4:27
  • 1
    C.__init__(self, name) <- this line is the issue. where is name coming from in class D():? Commented Jan 22, 2020 at 4:28

3 Answers 3

3

In class D, when you initialize it from C, you're not passing a value to the initialization of C, so it raises a NameError when it tries to pass it. You either need to allow D to take a value name and then pass it to C,

class C(object):
 def __init__(self, name):
 self.name = name
class D(C):
 def __init__(self, name):
 C.__init__(self, name) # name must be passed on initialization of D.

or define a default value for name in D.

class C(object):
 def __init__(self, name):
 self.name = name
class D(C):
 def __init__(self, name='Monty Python'):
 C.__init__(self, name) # allows you to only pass a name if you want to.
answered Jan 22, 2020 at 3:42
Sign up to request clarification or add additional context in comments.

Comments

2

Instead of using the parent class name use super() here so that later if you need to you can enable things like mixins, interfaces, abstract classes, etc.

Then you can also allow for those keyword arguments in the parent class to be used in the child class like this:

class D(C):
 def __init__(self,**kwargs):
 super(D,self).__init__(**kwargs)

Example usage:

In [349]: obj1 = D(name='test') 
In [350]: obj1.name 
Out[350]: 'test'
answered Jan 22, 2020 at 3:43

2 Comments

you don't have to give arguments to super() by default it will take the class.
I understand that. I left it this way to be clearer to someone learning the language.
0

never ever hard code the metho you inheriting instead of do super() by this if you want to change the method just change in the class name will be sufficient

there is no need to give argument's to super() in python3

 class C(object):
 def __init__(self, name):
 self.name = name
 class D(C):
 def __init__(self, name):
 super().__init__(self, name)
answered Jan 22, 2020 at 5:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.