Classes and Objects in Python
The starting point for the creation of objects is a class, which is a user-defined blueprint or prototype. Classes allow you to group data and functionality together. Creating a new class generates a new type of object, allowing for the creation of new instances of that type. Attributes can be applied to each class instance to save its state. Class instances can additionally have methods for altering their state (specified by their class).
A class generates a user-defined data structure that has its own data members and member methods that may be accessed and utilized by instantiating that class. A class is similar to an object’s blueprint.
class MyFirstClass: pass
Our very first object-oriented program is here! The class keyword introduces the class definition. This is followed by the class’s name (of our choosing), which is followed by a colon. The class name must adhere to the conventions for naming variables in Python, which state that names must begin with a letter or underscore and can only contain letters, underscores, or digits. Additionally, the Python style guide (look up PEP 8 on the internet) suggests class names be written using CapWords notation (the first letter of the class name should be capitalized, followed by any subsequent words).
We currently have a basic class, but it is largely ineffective. It doesn’t perform anything and doesn’t include any info. What must we do in order to give a certain object an attribute? In actuality, there is nothing unusual that needs to be done in the class definition. Dot notation allows us to assign any attributes to an instantiated object.
class Positional_point: pass point1 = Positional_point() point2 = Positional_point() point1.x = 6 point1.y = 4 point2.x = 3 point2.y = 5 print(point1.x, point1.y) print(point2.x, point2.y)
6 4 3 5
With no data or behaviors, the Positional_point class is created with this code. Then, to identify a point in two dimensions, it generates two instances of that class and gives each instance the x and y coordinates.
Allowing it to do something
Having objects with properties is nice, but object-oriented programming is truly about object interaction. We’re interested in triggering actions that have an effect on those properties. We have data; now we must include behaviors in our classes.
Let’s use our Position class to mimic a few activities. We may begin with the set technique, which moves the point to the (9, 7). This is an excellent first action because it does not require any arguments.
class Position: def set(self): self.x = 9 self.y = 7 point = Position() point.set() print(point.x, point.y)
Class with arguments
So, how can we pass a method with many arguments? Let’s create a new technique that allows us to transfer a point to any location other than the origin. One that accepts another Point object as input and returns the distance between them can also be included.
import math class Position: def move(self, x, y): self.x = x self.y = y def reset(self): self.move(0, 0) def calc_dist(self, other_point): x_diff = (self.x - other_point.x) ** 2 y_diff = (self.y - other_point.y) ** 2 return math.sqrt( x_diff + y_diff) point1 = Position() point2 = Position() point1.reset() point2.move(6, 8) print(point2.calc_dist(point1)) assert point2.calc_dist(point1) == point1.calc_dist(point2) point1.move(7, 4) print(point1.calc_dist(point2)) print(point1.calc_dist(point1))
10.0 4.123105625617661 0.0
A lot has occurred here. There are now three methods in the class. The move function takes two arguments, x, and y, and sets the values on the self-object, similar to the previous example’s reset method. The original reset technique is now called move because a reset is simply a move to a known place. The calc_dist method computes the distance between two places using the simple Pythagorean theorem. I hope you understand the arithmetic (**2 denotes squared, and math.sqrt computes a square root), but understanding how to construct methods isn’t necessary for our present emphasis. The sample code at the conclusion of the preceding example demonstrates how to call a method with arguments: just include the parameters inside the parenthesis, and access the method using the same dot notation. I just chose some positions at random to test the approaches. Each method is called by the test code, and the results are sent to the console. The assert function is a basic test tool; if the statement after assert evaluates to False, the program will exit (or zero, empty, or None). In this example, we utilize it to ensure that the distance remains constant regardless of which point invokes the calc_dist function on the other point.
The method declaration for class methods must have an additional initial argument. When we call the method, we do not offer a value for this parameter; Python does. We still need one parameter if we have a method that takes no arguments. This is analogous to the C++ pointer and the Java reference.
class Languages: lang1 = "Python" lang2 = "Java" def print_function(self): print("This is", self.lang1, "programming language.") print("This is", self.lang2, "programming language.") Mylang = Languages() print(Mylang.lang1) Mylang.print_function()
Python This is Python programming language. This is Java programming language.
The init method is analogous to C++ and Java constructors. Constructors are used to set the state of an object. A constructor, like a method, includes a set of statements (i.e. instructions) performed when an object is created. It starts when a class object is instantiated. The function is handy for performing any initialization on your object.
class Language: def __init__(self, name): self.name = name def print_function(self): print('Top programming languages are', self.name) Lang_list = Language('Java, Python, Go') Lang_list.print_function()
Top programming languages are Java, Python, Go