In this Python tutorial, let us discuss classes and objects in Python with appropriate examples.
Introduction of Python
Python is a widely-used general-purpose, high-level programming language and allows programming in OOPs paradigms.
The core benefit of Python is a large library that can be applied in the several fields as follows,
- Machine Learning
- GUI Applications
- Web frameworks like Django
- Image processing
- Web scraping Test frameworks
- Scientific computing
- Text processing and many more
Creating a Class
To create a class, use the keyword “class”.
Example to create a class
class MyClass: x = 5
The class named MyClass is created, with a property named x.
Creating an Object
We can use the class titled myClass to create an object.
Example to create an object
p1 = MyClass() print(p1.x)
An object named p1 is created. It will print the value of x.
The init() Function
All classes have a init() function call that is executed when the class initiates. The init() function is used to assign values to object properties or other operations, that is necessary to do when the object created.
Example to initiate a function
class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)
Objects can also contain methods.
Example to print name greeting using object
class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc()
Hello my name is John