After going through the basics of python, you would be interested to know more about further and bit more advance topics of the Python3 programming language.
This article covers them.
Please remember that Python completely works on indentation and it is advised to practice it a bit by running some programs. Use the tab key to provide indentation to your code.
This article is divided in following five sections:
- Classes
Just like every other Object Oriented Programming language Python supports classes. Let’s look at some points on Python classes.- Classes are created by keyword class.
- Attributes are the variables that belong to class.
- Attributes are always public and can be accessed using dot (.) operator. Eg.: Myclass.Myattribute
A sample E.g for classes:
# creates a class named MyClassclassMyClass:# assign the values to the MyClass attributesnumber=0name="noname"defMain():# Creating an object of the MyClass.# Here, 'me' is the objectme=MyClass()# Accessing the attributes of MyClass# using the dot(.) operatorme.number=1337me.name="Harssh"# str is an build-in function that# creates an stringprint(me.name+" "+str(me.number))# telling python that there is main in the program.if__name__=='__main__':Main()chevron_rightfilter_noneOutput :
Harssh 1337
- Methods
Method is a bunch of code that is intended to perform a particular task in your Python’s code.- Function that belongs to a class is called an Method.
- All methods require ‘self’ parameter. If you have coded in other OOP language you can think of ‘self’ as the ‘this’ keyword which is used for the current object. It unhides the current instance variable.’self’ mostly work like ‘this’.
- ‘def’ keyword is used to create a new method.
# A Python program to demonstrate working of class# methodsclassVector2D:x=0.0y=0.0# Creating a method named SetdefSet(self, x, y):self.x=xself.y=ydefMain():# vec is an object of class Vector2Dvec=Vector2D()# Passing values to the function Set# by using dot(.) operator.vec.Set(5,6)print("X: "+str(vec.x)+", Y: "+str(vec.y))if__name__=='__main__':Main()chevron_rightfilter_noneOutput :
X: 5, Y: 6
- Inheritance
Inheritance is defined as a way in which a particular class inherits features from its base class.Base class is also knows as ‘Superclass’ and the class which inherits from the Superclass is knows as ‘Subclass’
As shown in the figure the Derived class can inherit features from its base class, also it can define its own features too.# Syntax for inheritanceclassderived-classname(superclass-name)chevron_rightfilter_none# A Python program to demonstrate working of inheritanceclassPet:#__init__ is an constructor in Pythondef__init__(self, name, age):self.name=nameself.age=age# Class Cat inheriting from the class PetclassCat(Pet):def__init__(self, name, age):# calling the super-class function __init__# using the super() functionsuper().__init__(name, age)defMain():thePet=Pet("Pet",1)jess=Cat("Jess",3)# isinstance() function to check whether a class is# inherited from another classprint("Is jess a cat? "+str(isinstance(jess, Cat)))print("Is jess a pet? "+str(isinstance(jess, Pet)))print("Is the pet a cat? "+str(isinstance(thePet, Cat)))print("Is thePet a Pet? "+str(isinstance(thePet, Pet)))print(jess.name)if__name__=='__main__':Main()chevron_rightfilter_noneOutput :
Is jess a cat? True Is jess a pet? True Is the pet a cat? False Is thePet a Pet? True Jess
- Iterators
Iterators are objects that can be iterated upon.- Python uses the __iter__() method to return an iterator object of the class.
- The iterator object then uses the __next__() method to get the next item.
- for loops stops when StopIteration Exception is raised.
# This program will reverse the string that is passed# to it from the main functionclassReverse:def__init__(self, data):self.data=dataself.index=len(data)def__iter__(self):returnselfdef__next__(self):ifself.index==0:raiseStopIterationself.index-=1returnself.data[self.index]defMain():rev=Reverse('Drapsicle')forcharinrev:print(char)if__name__=='__main__':Main()chevron_rightfilter_noneOutput :
e l c i s p a r D
- Generators
- Another way of creating iterators.
- Uses a function rather than a separate class
- Generates the background code for the next() and iter() methods
- Uses a special statement called yield which saves the state of the generator and set a resume point for when next() is called again.
# A Python program to demonstrate working of GeneratorsdefReverse(data):# this is like counting from 100 to 1 by taking one(-1)# step backward.forindexinrange(len(data)-1,-1,-1):yielddata[index]defMain():rev=Reverse('Harssh')forcharinrev:print(char)data='Harssh'print(list(data[i]foriinrange(len(data)-1,-1,-1)))if__name__=="__main__":Main()chevron_rightfilter_noneOutput :
h s s r a H ['h', 's', 's', 'r', 'a', 'H']
This article is contributed by Harsh Wardhan Chaudhary (Intern) . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

