Python class nested class

Inner Class in Python

Python is an Object-Oriented Programming Language, everything in python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword.

Example of class

Python3

First of all, we have to understand the __init__() built-in method for understanding the meaning of classes. Whenever the class is being initiated, a method namely __init__() is always executed. An __init__() method is used to assign the values to object properties or to perform the other method that is required to complete when the object is created.

Example: class with __init__() method

Python3

Course : Campus Preparation Duration : As per your schedule

Inner Class in Python

A class defined in another class is known as an inner class or nested class. If an object is created using child class means inner class then the object can also be used by parent class or root class. A parent class can have one or more inner classes but generally inner classes are avoided.

We can make our code even more object-oriented by using an inner class. A single object of the class can hold multiple sub-objects. We can use multiple sub-objects to give a good structure to our program.

  • First, we create a class and then the constructor of the class.
  • After creating a class, we will create another class within that class, the class inside another class will be called an inner class.
Читайте также:  Класс для работы со временем java

Python3

Name: Green Name: Light Green Code: 024avc

Why inner class?

For the grouping of two or more classes. Suppose we have two classes remote and battery. Every remote needs a battery but a battery without a remote won’t be used. So, we make the Battery an inner class to the Remote. It helps us to save code. With the help of the inner class or nested class, we can hide the inner class from the outside world. Hence, Hiding the code is another good feature of the inner class. By using the inner class, we can easily understand the classes because the classes are closely related. We do not need to search for classes in the whole code, they all are almost together. Though inner or nested classes are not used widely in Python it will be a better feature to implement code because it is straightforward to organize when we use inner class or nested class.

# create NameOfOuterClass class class NameOfOuterClass: # Constructor method of outer class def __init__(self): self.NameOfVariable = Value # create Inner class object self.NameOfInnerClassObject = self.NameOfInnerClass() # create a NameOfInnerClass class class NameOfInnerClass: # Constructor method of inner class def __init__(self): self.NameOfVariable = Value # create object of outer class outer = NameOfOuterClass()

Types of inner classes are as follows:

Multiple inner class

The class contains one or more inner classes known as multiple inner classes. We can have multiple inner class in a class, it is easy to implement multiple inner classes.

Example: Multiple inner class

Источник

python inner class

An inner class or nested class is a defined entirely within the body of another class. If an object is created using a class, the object inside the root class can be used. A class can have more than one inner classes, but in general inner classes are avoided.

One of the most useful and powerful features of Python is its ability to nest classes within classes. A nested class is a class defined within another class, and inherits all the variables and methods of the parent class.

Inner class example

Python has inner classes. Inner classes are classes that are defined inside other classes. Inner classes have access to all the members of their outer classes.

Indention is very important when using inner classes. Every inner class should be indented by 4 spaces.

We create a class (Human) with one inner class (Head). An instance is created that calls a method in the inner class:

#!/usr/bin/env python

class Human:

def __init__(self):
self.name = ‘Guido’
self.head = self.Head()

class Head:
def talk(self):
return ‘talking. ‘

if __name__ == ‘__main__’:
guido = Human()
print(guido.name)
print(guido.head.talk())

In the program above we have the inner class Head() which has its own method. An inner class can have both methods and variables. In this example the constructor of the class Human (init) creates a new head object.

Multiple inner classes

#!/usr/bin/env python

class Human:

def __init__(self):
self.name = ‘Guido’
self.head = self.Head()
self.brain = self.Brain()

class Head:
def talk(self):
return ‘talking. ‘

class Brain:
def think(self):
return ‘thinking. ‘

if __name__ == ‘__main__’:
guido = Human()
print(guido.name)
print(guido.head.talk())
print(guido.brain.think())

By using inner classes you can make your code even more object orientated. A single object can hold several sub objects. We can use them to add more structure to our programs.

Why inner class?

An inner class lets you group classes. They have some advantages over using only distinct classes.

Inner classes (sometimes callled nested classes) are not widely used in Python.

If you are new to Python programming, I highly recommend this book.

Hi Frank! I just wonder why __name__ here set to __main__?
I can figure the guido.name head.talk(), brain.think(), and the other parts and how it works.
But I’m totally confuse, about __main__ condition.
Is it because __name__ is private variable?
What if I replace __main__ here with __main, like your example variable structure in encapsulation?
An answer will be valuable to me.
Ps. I’m just totally beginner, but your tutorial are the easiest one to be understood.
Thank’s

Hi! Thanks! Python has an execution entry point called main. When you execute a Python script, it is used as the main function (starting point of the program) if the __name__ attribute is set to «__main__».

If you import this script as a module, the __name__ is set to the name of the script/module and it will not be executed.

The code below is used to execute some code only if the file was run directly, and not imported.

if __name__ == «__main__»:
# execute only if run as a script
main()

Let us do an example, we create a python file called file.py:

#!/usr/bin/env python

if __name__ == «__main__»:
print ‘Hello from file.py’
import file

if __name__ == «__main__»:
print ‘Hello from file2.py’

If we run either of these two scripts, it will execute only the code in __main__. Thus the output is either «Hello from file.py» or «Hello from file2.py».
However, if we change file.py to:

#!/usr/bin/env python

print ‘Hello from file.py’

and run file2.py, it will execute all code in file.py and in the __main__ of file2.py, thus outputting:

Hello from file.py
Hello from file2.py

In short, we need __main__ if we want to couple python files together. Without __main__, Python will execute all code from every file that is imported.
If you change to __main it will not execute or use it as starting point of a script because __main__ is a special variable in Python.

That means that you do not have to use __main__ at all if you are not importing the script anywhere, meaning this will work too:

#!/usr/bin/env python

class Human:

def __init__(self):
self.name = ‘Guido’
self.head = self.Head()
self.brain = self.Brain()

class Head:
def talk(self):
return ‘talking. ‘

class Brain:
def think(self):
return ‘thinking. ‘

guido = Human()
print guido.name
print guido.head.talk()
print guido.brain.think()

In your (files).py examples, if the __main__ code in file.py are removed, it will make file.py become regular class, and file2.py become the main class, like in Java?
If that so, in my mind, simple Java program always have main class (public static void main) that will execute the listed program, while in python some simple program didn’t always need __main__ to execute the listed program.
Am I correct?
Sorry, completely new to python world, and totally forgot java environment after years.
Thank’s for your patience, Frank!

Yes, if __main__ is removed, file.py will become a regular class. Python will execute anything that is on the 0th level of indention from file.py, which is different form Java. If file.py would contain a class with methods, it can be included without any problems. The code below demonstrates:

#!/usr/bin/env python

class Test:
def test(self):
print ‘Hello from file.py’
from file import *

if __name__ == «__main__»:
print ‘Hello from file2.py’
t = Test()
t.test()

In usage its similar to Java’s public static void main, with the exception that Python will execute any statement on the 0th level of indention.

Hi Frank,
I was wondering how would we show a content of a variable defined in the parent class in the inner class?

As far as i know, inner classes have no way of accessing outer class variables.

Источник

Nested or Inner Classes in Python

A nested or inner class is contained within another class. This could be for reasons of encapsulation, where the inner class is not useful by itself.

Here is an example of how the classes are laid out.

class A: class B: pass pass

An inner class in python is a distinct entity in that it does not automatically get access to the outer class members in any special way.

2. Implementing an Iterator without an Inner Class

Let us examine the use of an inner class to implement an iterator. An iterator is an object that can be used in a for-loop for iterating over a collection.

Consider this example of Cats class which stores a bunch of cat names. You can use the add() method to add a cat. Since the class also implements the __iter__() special method to return an iterator, an instance of this class can be used directly in a for-loop.

An iterator is an object that supports the next() method and raises the StopIteration exception when the end of the collection is reached.

class Cats: def __init__(self): self.cats = [] self.cur = 0 def add(self, name): self.cats.append(name) return self def __iter__(self): return self def next(self): i = self.cur if i >= len(self.cats): raise StopIteration self.cur += 1 return self.cats[i]

Here is how you can use this class.

a = Cats() a.add('joe').add('jack').add('fink').add('dink') for c in a: print c # prints joe jack fink dink

3. Making the Iterator an Inner Class

Now the above implementation has a design fault. It combines the functionalities of the Cats object with an iterator object. Functionally the two entities are separate and this should be reflected in code. Let us do this by moving the iterator functionality into a separate class. And since the iterator class is specialized to the Cats class, it will not be useful outside of the Cats class and we should make it an inner class.

Here is the implementation where the iterator has been separated into the _cat_iter class with the required implementation of the next() method. Also notice that the __iter__() method returns an instance of the iterator class.

class Cats: class _cat_iter: def __init__(self, cats): self.cats = cats self.cur = 0 def next(self): i = self.cur if i >= len(self.cats): raise StopIteration self.cur += 1 return self.cats[i] def __init__(self): self.cats = [] def add(self, name): self.cats.append(name) return self def __iter__(self): return Cats._cat_iter(self.cats)

Since the interface to the Cats class did not change, there is no change in the client code.

a = Cats() a.add('joe').add('jack').add('fink').add('dink') for c in a: print c

Conclusion

Python does have support for nested or inner classes. These classes can be used when you do not want to expose the class, and it is closely related to another class.

Источник

Оцените статью