0% found this document useful (0 votes)
31 views7 pages

Python Class Basics and Examples

Uploaded by

nananana
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views7 pages

Python Class Basics and Examples

Uploaded by

nananana
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Classes in Python

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.

In Python, you can define a class using the class keyword followed by the class
name. Here’s a basic example of how to write a class in Python:
class Point:
x = 5
y = 7

p = Point()
print(p.x, p.y)

A class Point is created, with two properties x and y.


An object p of the Point class is created. The class attributes x and y of are printed.

The __init__() function


The example provided above represents a class in its most basic form and may not
be particularly useful in real-world applications. To grasp the significance of classes, we
must comprehend the __init__() function.
If a class has a function __init__(), it is always executed when the class is 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.

In Python, self is a convention used to refer to the instance of the class itself. When
defining methods within a class, including the __init__() method, the first parameter is
always self. This parameter is used to access the attributes and methods of the instance
within the class.

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

p = Point(3, 6)
print(p.x, p.y)

The class Point represents a point in a two-dimensional coordinate system. It has


two attributes x and y which define the coordinates of the point.
The __init__() method is used as a constructor to initialize the attributes x and y
with the values passed as arguments when an instance of the class is created.
In Python, you don’t need to declare class variables separately (like x, y) ahead
of time because:
• Instance variables in Python are created dynamically
When you write:
self.x = x
self.y = y
Python automatically creates these attributes within the object (the instance of the
class) at the moment you assign to them in the __init__ method.

Python is a dynamically typed language. Objects are flexible, and in many ways
behave like dictionaries. You can even add new fields on the fly:

class Rectangle:
def __init__(self, x, y):
self.x = x
self.y = y

r = Rectangle(2, 3)
[Link] = "red" # This works! Adds a new attribute dynamicall
print(r.x, r.y,[Link])

This gives you flexibility, but it also means you have to be careful not to make
mistakes with attribute names or structures.

The __str__() function


The __str__() function controls what should be returned when the class object is
represented as a string.
If the __str__() function is not set, the string representation of the object is
returned.

The string representation of an object without the __str__() function:


class Point:
def __init__(self, x, y):
self.x = x
self.y = y

p = Point(3, 6)
print(p)

The string representation of an object with the __str__() function:


class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __str__(self):
return f'({self.x}, {self.y})'
# return str(self.x) + " " + str(self.y)

p = Point(3, 6)
print(p)

Object Methods
Objects can also contain methods. Methods in objects are functions that belong to
the object. Let us create a method f in the Point class:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def f(self):
print("(" + str(self.x) + "," + str(self.y) + ")")

p = Point(3, 6)
p.f()

The first parameter of the method does not have to be named self , you can call it
whatever you like, but it must be the first parameter of any function in the class.
class Point:
def __init__(my, x, y):
my.x = x
my.y = y

def f(qq):
print("(" + str(qq.x) + "," + str(qq.y) + ")")

p = Point(3, 6)
p.f()

Comparison methods
Consider the comparison methods in Python – these are called “dunder methods”
(short for “double underscore”).

Operator Method
< __lt__
<= __le__
== __eq__
!= __ne__
>= __ge__
> __gt__

When you write something like:


if a < b:
Python actually runs:
a.__lt__(b)
So if you’re comparing custom objects like:

class Box:
def __lt__(self, other):
return [Link] < [Link]

then box1 < box2 will work based on your logic.

Example. Let’s define a custom class called Box, which represents a 3D box with
dimensions x, y, and z.
The following program creates two boxes and compares them based on their
volume, not their dimensions. Even though their sizes are ordered differently, their
volumes are equal, so they are considered equal using ==.

class Box:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z

def getVolume(self):
return self.x * self.y * self.z

def __str__(self):
return "(" + str(self.x) + "," + str(self.y) + "," + str(self.z)
+")"

def __gt__(self, other):


return [Link]() > [Link]()

def __lt__(self, other):


return [Link]() < [Link]()

def __eq__(self, other):


return [Link]() == [Link]()

a = Box(2,4,5)
b = Box(4,5,2)

print(a, "Volume:", [Link]()) # (2,4,5) Volume: 40


print(b, "Volume:", [Link]()) # (4,5,2) Volume: 40
print(a > b, a == b, a < b) # False True False

E-OLYMP 4817. Rectangle Find the perimeter and area of the rectangle.

Input. Each line represents a separate test and contains the length n and the width
m (1 ≤ n, m ≤ 1000) of the rectangle.

Output. For each test, print the perimeter and area of the rectangle in one line.
Sample input Sample output
3 1 8 3
5 3 16 15
10 7 34 70

► The following program computes the perimeter and area of a rectangle.


import sys

class Rectangle:
def __init__(self, x, y):
self.x = x
self.y = y

def perimeter(self):
return (self.x + self.y) * 2

def area(self):
return self.x * self.y

for line in [Link]:


n, m = map(int, [Link]())
r = Rectangle(n, m)
print([Link](), [Link]())

E-OLYMP 972. Sorting time Sort the moments of time according to the specified
criteria.

Input. The first line contains the number n (1 ≤ n ≤ 100), followed by n moments
of time. Each moment of time is specified by three integers: hours (from 0 to 23),
minutes (from 0 to 60) and seconds (from 0 to 60).

Output. Print the moments of time sorted in non-decreasing order. Each moment
of time should be displayed as three integers, without leading zeros.

Sample input Sample output


4 7 30 0
10 20 30 10 20 30
7 30 00 13 30 30
23 59 59 23 59 59
13 30 30

► Implementation with cmp_to_key function.


from functools import cmp_to_key
import sys

class Time:
def __init__(self, h, m, s):
self.h = h
self.m = m
self.s = s

def __str__(self):
return str(self.h) + " " + str(self.m) + " " + str(self.s)

def f(a, b):


if a.h == b.h and a.m == b.m:
return a.s - b.s
if a.h == b.h:
return a.m - b.m
return a.h - b.h

n = int(input())
time = []
for line in [Link]:
h, m ,s = map(int, [Link]())
[Link](Time(h, m, s))

time = sorted(time, key = cmp_to_key(f))

for t in time:
print(t)

__lt__ function
The function def __lt__(self, other): in Python is a special method used to define
the “less than” comparison between two objects – specifically, it’s what Python uses
when you do a < b. In the context of sorting, Python calls __lt__ internally to figure out
how to compare and order elements.

def __lt__(self, other):


• self is the current object (time1)
• other is the object it’s being compared to (time2)
• The method should return True if self is considered less than other, and
False otherwise.

class Time:
def __init__(self, h, m, s):
self.h = h
self.m = m
self.s = s

def __str__(self):
return str(self.h) + " " + str(self.m) + " " + str(self.s)

def __lt__(self, other):


if self.h == other.h and self.m == other.m:
return self.s < other.s
if self.h == other.h:
return self.m < other.m
return self.h < other.h

n = int(input())
time = []
for _ in range(n):
h, m ,s = map(int, input().split())
[Link](Time(h, m, s))

[Link]()

for t in time:
print(t)

Eolymp problems
Geometric classes
4817. Rectangle (implement class rectangle)
3171. Point within a circle (implement class point, circle)
2132. Point on a line (implement class point, line)
2130. The angle between the vectors (implement class vector)
925. Perimeter and area of triangle (implement class triangle)
Sort the classes
972. Sorting time
8637. Sort the points
10246. ACM Sort
10263. Sort the people
8197. Class Time

You might also like