?print-pdf
' Created for
class ClassName:
def __init__(self, parameters):
# Constructor method to initialize attributes
self.attribute = value
def method(self):
# Method to define behavior
pass
object_name = ClassName()
# create objects of class Person:
pesho = Person()
maria = Person()
# let's check:
print( type(pesho) )
print( type(maria) )
# <class '__main__.Person'>
# <class '__main__.Person'>
class
have same type
, but they are different entities:
class Person:
pass
maria = Person()
pesho = Person()
print( maria == pesho)
#False
__init__()
method__init__()
method__init__()
method (called Class Constructor in other languages) is a special method which is called automatically when each new object is created.__init__()
method defines the action which will happens when a new object instance is created.
class ClassName:
def __init__(self):
pass
# class definition
class ClassA:
def __init__(self):
print("An object of ClassA is created!")
# objects creation:
obj1 = ClassA()
obj2 = ClassA()
# output:
# An object of ClassA is created!
# An object of ClassA is created!
self
parameter
class ClassName:
def __init__(self, val1, val2):
self.atr1 = val1
self.atr2 = val2
self
refers to the instance of the class and allows access to attributes and methods.self
will take (automatically) a reference to the object being created.self
class Person:
def __init__(self, name, age):
# set object attributes values:
self.name = name
self.age = age
def greet(self):
print(f"Hi there! I'm {self.name}, {self.age} years old!")
maria = Person("Maria Popova", 25)
pesho = Person("Pesho", 27)
maria.greet()
pesho.greet()
# Hi there! I'm Maria Popova, 25 years old!
# Hi there! I'm Pesho, 27 years old!
class Person:
def __init__(self, name, age):
# set instance attributes
self.name = name
self.age = age
maria = Person('Maria', 23)
# access object attribute for writing:
maria.age = 24
# access object attribute for reading:
print(maria.age) # 24
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Maria Popova", 25)
person2 = Person("Petar Ivanov", 34)
print(person1.name) # Maria Popova
print(person1.age) # 25
print(person2.name) # Petar Ivanov
print(person2.age) # 34
class Person:
name = "Anonymous"
age = 100
maria = Person()
petar = Person()
print(maria.name, maria.age) # Anonymous 100
print(petar.name, petar.age) # Anonymous 100
print(Person.name, Person.age) # Anonymous 100
class Person:
name = "Anonymous"
def __init__(self, name):
self.name = name
maria = Person("Maria Popova")
petar = Person("Petar Ivanov")
print(maria.name) # Maria Popova
print(petar.name) # Petar Ivanov
print(Person.name) # Anonymous
class Person:
count = 0
def __init__(self, name):
self.name = name
Person.count += 1
maria = Person("Maria Popova")
petar = Person("Petar Ivanov")
ivan = Person("Ivan Petrov")
print(Person.count) # 3
class Circle:
PI = 3.14159 # Class attribute
def __init__(self, radius):
self.radius = radius
def area(self):
return Circle.PI * self.radius ** 2
c = Circle(5)
print(c.area()) # Output: 78.53975
class User:
default_role = "guest"
def __init__(self, name, role=None):
self.name = name
self.role = role if role else User.default_role
u1 = User("Alice")
u2 = User("Bob", "admin")
print(u1.role) # Output: guest
print(u2.role) # Output: admin
__dict__
, which store an object's (writeable) attributes
class Person:
count = 0
def __init__(self, name):
self.name = name
Person.count += 1
maria = Person("Maria Popova")
print(maria.__dict__) # {'name': 'Maria Popova'}
class ClassName:
def method_name(self):
pass
self
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# define instance method
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
maria = Person('Maria', 23)
# call greet() method on maria. python will send the maria object reference to the self parameter.
maria.greet()
# Hello, my name is Maria and I am 23 years old.
class A:
def method1(self, obj):
print(self)
print(obj)
print(self==obj)
a = A()
# lets check if a == self
a.method1(a)
# <__main__.A object at 0x7fa44994df40>
# <__main__.A object at 0x7fa44994df40>
# True
@classmethod
decorator.cls
, which reference to the class itself.
class Person:
count = 0
@classmethod
def increment_count(cls):
# do additional actions or checks...
cls.count += 1
def __init__(self, name):
self.name = name
Person.increment_count()
maria = Person("Maria Popova")
petar = Person("Petar Ivanov")
ivan = Person("Ivan Petrov")
print(Person.count)
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
@staticmethod
def calculate_fuel_efficiency(distance, fuel_used):
return distance / fuel_used
__init__()
method in Python, there are many other predefined special methods, also called magic (or dunder) methods, which have the same notation form:
__magic__()
__str__
method is meant to return a human-readable string representation of an object.__str__()
method will be invoked when you call the str(), format() or print() functions of a class instance
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"name = {self.name}\nage = {self.age}\n"
maria = Person("Maria Popova", 25)
print(maria)
# name = Maria Popova
# age = 25
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"x = {self.x}, y = {self.y}"
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2 # Uses __add__
print(p3)
# x = 4, y = 6
class Employee:
"""Represents an employee with a name, ID, salary, and department."""
def __init__(self, name, emp_id, salary, department):
"""Initializes an Employee object with the given attributes."""
self.name = name
self.emp_id = emp_id
self.salary = salary
self.department = department
def calculate_salary(self, hours_worked=40):
"""Calculates the employee's salary, including overtime if applicable."""
overtime = 0
if hours_worked > 40:
overtime = hours_worked - 40
overtime_pay = overtime * (self.salary / 2080) # Assuming 52 weeks per year, 40 hours per week
self.salary += overtime_pay
def __str__(self):
"""Returns a formatted string containing the employee's details. Called automatically by print()"""
return f"Name: {self.name}\nID: {self.emp_id}\nSalary: {self.salary:.2f}\nDepartment: {self.department}"
# Example usage:
employee1 = Employee("Ivan Ivanov", 12345, 50000, "Engineering")
employee1.calculate_salary(45) # Calculate salary with overtime
print(employee1)
# Name: Ivan Ivanov
# ID: 12345
# Salary: 50120.19
# Department: Engineering
class Employee:
"""Represents an employee with a name, ID, salary, and department."""
def __init__(self, name, emp_id, salary, department):
"""Initializes an Employee object with the given attributes."""
self.name = name
self.emp_id = emp_id
self.salary = salary
self.department = department
# Create 5 employee objects with different salaries
employees = [
Employee("Ivan Petrov", 1234567890, 50000, "Engineering"),
Employee("Maria Ivanova", 9876543210, 65000, "Marketing"),
Employee("Mihail Georgiev", 2345678901, 48000, "Sales"),
Employee("Alisa Stoyanova", 3456789012, 52000, "Human Resources"),
Employee("Bogomil Nikolov", 5678901234, 70000, "Finance"),
]
# Find the employee with the highest salary
highest_earner = max(employees, key=lambda emp: emp.salary)
# Print the details of the employee with the highest salary
print(f"Employee with the highest salary:")
print(f"Name: {highest_earner.name}")
print(f"ID: {highest_earner.emp_id}")
print(f"Salary: ${highest_earner.salary}")
print(f"Department: {highest_earner.department}")
# Employee with the highest salary:
# Name: Bogomil Nikolov
# ID: 5678901234
# Salary: $70000
# Department: Finance
class Car:
"""Represents a car with specific attributes and functionalities."""
def __init__(self, manufacturer, model, year, color, mileage):
"""Initializes a Car object with the given attributes."""
self.manufacturer = manufacturer
self.model = model
self.year = year
self.color = color
self.mileage = mileage
def accelerate(self, speed_increase):
"""Simulates accelerating the car by increasing its speed."""
# Add safety checks and speed limits here
print(f"Car is accelerating, speed increased by {speed_increase} mph.")
def brake(self, speed_decrease):
"""Simulates braking the car by decreasing its speed."""
# Add safety checks and minimum speed requirement here
print(f"Car is braking, speed decreased by {speed_decrease} mph.")
def __str__(self):
"""Returns a formatted string of the car's details. Called automatically by print()"""
return f"Manufacturer: {self.manufacturer}\nModel: {self.model}\nYear: {self.year}\nColor: {self.color}\nMileage: {self.mileage}"
# Example usage:
my_car = Car("Toyota", "Camry", 2020, "Silver", 30000)
my_car.accelerate(20)
my_car.brake(10)
print(my_car)
# Car is accelerating, speed increased by 20 mph.
# Car is braking, speed decreased by 10 mph.
# Manufacturer: Toyota
# Model: Camry
# Year: 2020
# Color: Silver
# Mileage: 30000
class BaseClass:
pass
class DerivedClass(BaseClass):
pass
class Person():
# Constructor to initialize name and age attributes
def __init__(self, name, age):
self.name = name
self.age = age
# Method to print a greeting message
def greet(self):
print(f"Hi, I'm {self.name} and I'm {self.age} years old. ")
# Employee class inherits from Person class, no additional functionality is added
class Employee(Person):
pass
# Create an Employee object named maria with name "Maria" and age 20
maria = Employee("Maria", 20)
# Call the greet method (inherited from Person) on the maria object
maria.greet()
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hi, I'm {self.name} and I'm {self.age} years old. ")
class Employee(Person):
# Overriding the greet method to customize greeting for employees
def greet(self):
print(f"Hi, I'm the employee {self.name}, {self.age} years old. ")
# Create a Person object named maria with name "Maria" and age 20
maria = Person("Maria", 20)
# Create an Employee object named petar with name "Petar" and age 34
petar = Employee("Petar", 34)
# Call the greet method on maria (Person object)
maria.greet()
# Call the greet method on petar (Employee object, using overridden method)
petar.greet()
# Output:
# Hi, I'm Maria and I'm 20 years old.
# Hi, I'm the employee Petar, 34 years old.
super()
function
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hi, I'm {self.name} and I'm {self.age} years old. ")
class Employee(Person):
def __init__(self, name, age, salary):
super().__init__(name, age) # call Person __init__
self.salary = salary
def greet(self):
super().greet() # # call Person greet_
print(f'My salary is {self.salary}')
maria = Employee("Maria", 20, 7300)
maria.greet()
Naming | Type | Meaning |
---|---|---|
name | Public | Attributes, that can be freely used inside or outside of a class definition. |
_name | Protected | Protected attributes are intended to be used only within the class and its subclasses.. |
__name | Private | This kind of attribute should be inaccessible and invisible outside the class. It's neither possible to read nor write to those attributes, except inside of the class definition itself. |
class Person:
def __init__(self, name, age):
self.name = name
self.__age = age # private attribute, cannot be accessed directly outside the class
def __str__(self):
return f"name = {self.name}; __age = {self.__age}"
maria = Person("Maria Popova", 25)
# Attempt to change Maria's age by directly accessing the private attribute
maria.__age = 100 # This won't change the private attribute __age,
# The actual __age value remains the same (private attributes are not directly accessible)
print(maria) # Output: name = Maria Popova; __age = 25
_ClassName
, known as name mangling.
class Person:
def __init__(self, name, age):
self.name = name
self.__age = age
def __str__(self):
return f"name = {self.name}; __age = {self.__age}"
maria = Person("Maria Popova", 25)
# let's try to change Maria's age -
maria._Person__age = 100
print(maria) # name = Maria Popova; __age = 100
One of my goals for Python was to make it so that all objects were "first class." By this, I meant that I wanted all objects that could be named in the language (e.g., integers, strings, functions, classes, modules, methods, etc.) to have equal status. That is, they can be assigned to variables, placed in lists, stored in dictionaries, passed as arguments, and so forth.A blog post by Guido van Rossum
name = value
x = 10 # x points to the value 10
y = x # y now also points to the value 10
print(x) # Output: 10
print(y) # Output: 10
# Changing y does not affect x since integers are immutable.
# So a new object is created and y points to it
y = 20
print(x) # Output: 10
print(y) # Output: 20
These slides are based on
customised version of
framework