Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using super() in nested classes

Tags:

Imagine this:

class A(object):     class B(object):         def __init__(self):             super(B, self).__init__() 

This creates an error:

 NameError: global name B is not defined. 

I've tried A.B, but then it says that A is not defined.

Update:

I've found the problem.

I've had a class like this:

class A(object):     class B(object):         def __init__(self):             super(B, self).__init__()      someattribute = B() 

In that scope, A isn't defined yet.

like image 911
Georg Schölly Avatar asked Dec 01 '09 10:12

Georg Schölly


People also ask

What is the use of the super () function?

The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.

What does super () do and where we have to use it?

The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

Why do we need super () in an extended class Python?

The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super.

What is super __init__?

The “__init__” is a reserved method in python classes. It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. Python super() The super() function allows us to avoid using the base class name explicitly.


1 Answers

I'm not sure why A.B is not working correctly for you, as it should.. Here's some shell output that works:

>>> class A(object): ...   class B(object): ...     def __init__(self): ...       super(A.B, self).__init__() ...   def getB(self): ...     return A.B() ...  >>> A().getB() <__main__.B object at 0x100496410> 
like image 151
Douglas Mayle Avatar answered Sep 30 '22 03:09

Douglas Mayle