In programming concepts, a class refers to a blueprint for the object, and a class is a template that describes an object’s specifics.
Class is like a drawing of a Dog with labels on it. In this case, a dog is an object with all the information about its name, colors, size, and other things.
To create a class, use the keyword class.
Basic Syntax
class MyClass: marks = 100
Let’s take an example of Dog class,
Example
class Dog: pass
We created a dog class using the class keyword in the above illustration.
Let’s take an example to see why you need to make a class. Say you wanted to keep track of the number of dogs with different characteristics, such as breed or age. If you use a list, the first item could be the dog’s breed, and the second could be its age. Let’s say there are 100 different dogs. How would you know which one is which? What would you do if you wanted to give these dogs other traits which are not organized?
A few things about the Python class:
For example:
class Dog: pass
For example:
Myclass.Myattribute
The object is an entity that is connected to a state and activity.
Any physical device, such as a mouse, keyboard, chair, table, pen, etc., may be used. Arrays, dictionaries, strings, floating-point numbers, and even integers are all examples of objects. Any single string or integer, more specifically, is an object.
An object has a state, identity, and behavior:
Dog Example:
Let’s look at the class dog’s example to understand better the state, behavior, and identity.
You may infer from the behavior whether the dog is eating or sleeping.
A class gets instantiated into an object (instance). In Python, only the object’s description is specified when a class is defined. As a result, no memory or storage is assigned.
Now we can utilize the Class named MyClass to create objects:
dogObject = Dog() dogObject.marks
These examples are classes and objects in their most basic form and therefore are not particularly applicable to real-world applications. To comprehend the concept of classes, we must understand the __init__() and self function.
The ‘self’ parameter is the reference to the Class’s current instance and is used to access class variables.
It does not have to be called self; you can call it whatever you prefer; nonetheless, it must be the first parameter of every class function.
The __init__ method is comparable to Java and C++ constructors, executed when a class object is instantiated.
The method is useful for any object initialization you may require. You can use the __init__() function to assign values to object properties or do other required activities when the object is created:
Now let’s create several objects utilizing the self and __init__ methods to define a class.
class Dog: def __init__(self, name, age): self.name = name self.age = age
Let’s spice up the Dog class by defining some required properties for all Dog instances. Name, age, coat color, and breed are some available options. To keep things simple, we will only utilize name and age.
. init__ defines the required properties for all Dog objects(). Whenever a new Dog object is created, init__() sets the object’s initial state by assigning values to its properties. Thus,. init__() initializes each newly created class instance. init__() accepts any number of parameters, but the first parameter is always a variable named self. At a new class instance creation, the instance is automatically provided to the self parameter in. init__(), allowing new attributes to be defined on the object.
Let’s modify the Dog class to include an. init__() method that creates the.name and.age attributes:
# Dog Class class Dog: # class attribute breed = "Dog" # instance attribute def __init__(self, name, age): self.name = name self.age = age # instantiate the Dog class Tommy = Dog("Tommy", 2) Rocky = Dog("Rocky", 7) # access the class attributes print("Tommy is a {}".format(Tommy.__class__.breed)) print("Rocky is also a {}".format(Rocky.__class__.breed)) # access the instance attributes print("{} is {} years old".format( Tommy.name, Tommy.age)) print("{} is {} years old".format( Rocky.name, Rocky.age))
Output
Tommy is a Dog Rocky is also a Dog Tommy is 2 years old Rocky is 7 years old
In the above code, we built a class named dog. We define attributes next, and the attributes are distinguishing features of an object. These attributes are defined within the Class’s __init__ method.
def __init__(self, name, age): self.name = name self.age = age
The initializer method is executed immediately after the object is formed. Then, instances of the Dog class are created. Here, Tommy and Rocky reference our new objects (value).
Tommy = Dog(“Tommy”, 2)
Rocky = Dog(“Rocky”, 7)
All instances of a class possess the same class attributes. We may access the class attribute using ‘_class_ .breed’ to obtain the class attribute. Similarly, the instance characteristics are accessed via ‘Tommy.name’ and ‘Tommy.age’. However, instance characteristics are unique for each class instance.
print(“Tommy is a {}”.format(Tommy.__class__.breed))
print(“Rocky is also a {}”.format(Rocky.__class__.breed))
Methods are functions defined within a class’s body. They are used to define an object’s behavior.
Example Creating Class and objects with methods
#!/usr/bin/python # -*- coding: utf-8 -*- # create the Dog class class Dog: # class attribute breed = 'Dog' # instance attribute def __init__(self, name, age): self.name = name self.age = age # instance method def bark(self): return '{} barks woof{}'.format(self.name) def walk(self, speed): return '{} walks'.format(self.name, speed) # instantiate the Dog class Tommy = Dog('Tommy', 2) Rocky = Dog('Rocky', 7) # call our instance methods print Tommy.bark() print Tommy.walk("'slow'") print Rocky.bark() print Rocky.walk("'fast'")
Output
In the exceeding code, we define two functions i.e.bark() and walk(). These are instance methods because they are called on an instance object, i.e., Tommy and Rocky.