Below is a simple Python program that creates a class with single method.
As we can see above, we create a new class using the class statement and the name of the class. This is followed by an indented block of statements which form the body of the class. In this case, we have defined a single method in the class.
Next, we create an object/instance of this class using the name of the class followed by a pair of parentheses.
- Class methods must have an extra first parameter in method definition. We do not give a value for this parameter when we call the method, Python provides it
- If we have a method which takes no arguments, then we still have to have one argument – the self. See fun() in above simple example.
- This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about.
The __init__ method
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.
Hello, my name is Shwetanshu
Here, we define the __init__ method as taking a parameter name (along with the usual self). .
Class and Instance Variables (Or attributes)
In Python, instance variables are variables whose value is assigned inside a constructor or method with self.
Class variables are variables whose value is assigned in class.
We can define instance variables inside normal methods also.
How to create an empty class?
We can create an empty class using pass statement in Python.
This article is contributed by Shwetanshu Rohatgi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
- Changing Class Members in Python
- Overriding Nested Class members in Python
- Object Oriented Programming in C++
- Introduction of Object Oriented Programming
- Python | Matplotlib Sub plotting using object oriented API
- Python | Matplotlib Graph plotting using object oriented API
- Object oriented testing in Python
- How to create a list of object in Python class
- CBSE Class 11 | Concepts of Programming Methodology
- Python | Using variable outside and inside the class and method
- OOP in Python | Set 3 (Inheritance, examples of object, issubclass and super)
- Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
- Class and Instance Attributes in Python
- Subclass and methods of Shelve class in Python
- Python IMDbPY – Info set to keys of Movie object
- Python IMDbPY – Info set to keys of Person object
- StringTokenizer class in Java with example | Set 1 ( Constructors)
- String class in Java | Set 1
- Difference Between Go and Python Programming Language