Classes you may like
Object Oriented Programming in Python | Set 1 (Class, Object and Members)
Below is a simple Python program that creates a class with a 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 that 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.
The object is an entity that has a state and behavior associated with it. It may be any real-world object like the mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects. More specifically, any single integer or any single string is an object. The number 12 is an object, the string “Hello, world” is an object, a list is an object that can hold other objects, and so on. You’ve been using objects all along and may not even realize it.
A class is a blueprint that defines the variables and the methods (Characteristics) common to all objects of a certain kind.
Example: If Car is a class, then Audi A6 is an object of the Car class. All cars share similar features like 4 wheels, 1 steering wheel, windows, breaks etc. Audi A6 (The Car object) has all these features. The self
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
Create a class named MyClass, with a property named x:
class MyClass: x = 5
Now we can use the class named MyClass to create objects:
Create an object named p1, and print the value of x:
p1 = MyClass() print(p1.x)
The __init__() Function
The examples above are classes and objects in their simplest form, and are not really useful in real life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being initiated.
Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:
Create a class named Person, use the __init__() function to assign values for name and age:
class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)
For more, checkout Geeks For Geeks and W3Schools.