ALX LESSON
0x06 Python -
Classes and
Objects
python - Programming
TABLE OF CONTENTS
01 02
Overview Learning
topics Objectives
03 04
Quiz hands on lab
questions practice
01
OVERVIEW topics
Topics
What is OOP
“first-class everything”
What is a class
What is an object and an instance
python What is the difference between a class and an
object or instance
Programming What is an attribute
Topics
What are and how to use public, protected and
private attributes
What is self
What is a method
Topics What is the special __init__ method and how to use it
What is Data Abstraction, Data Encapsulation, and
Information Hiding
What is a property
What is the difference between an attribute and a property
in Python
What is the Pythonic way to write getters and setters in
python Python
Programming How to dynamically create arbitrary new attributes for
existing instances of a class
Topics
How to bind attributes to object and classes
What is the __dict__ of a class and/or instance of a class
and what does it contain
How does Python find the attributes of an object or class
How to use the getattr function
Slides On Telegram
https://t.me/alx_2023
python
Programming
Topics
Slides exist on telegram
@alx_2023ch
02
Learning Objectives
What is OOP
Object-Oriented Programming (OOP) is a programming paradigm that revolves
around the concept of "objects." It's a way of designing and organizing code that
models real-world entities, their properties, and their interactions.
Python supports object-oriented programming, objects are instances of classes.
first-class everything
Class Definition Syntax:
class ClassName:
# Statement-1
.
.
.
# Statement-N
What is a class
Class: A class is a blueprint for creating objects. It defines the attributes and
methods that the objects will have. It's like a template or a prototype.
What is an object and an instance
Object: An object is an instance of a class. It represents a specific entity with its
own set of attributes and behaviors.
An object encapsulates both data (attributes) and the methods (functions) that
operate on that data. Objects have specific values for their attributes, making
them distinct instances of a class.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
car1 = Car("Toyota", "Camry") # Creating an instance/object of Car
car2 = Car("Tesla", "Model 3") # Creating another instance/object of
difference between class and an object or instance
What is an attribute
An attribute, in the context of object-oriented programming (OOP), refers to a
piece of data that is associated with an object.
class Person:
def __init__(self, name, age):
self.name = name # 'name' is an attribute
self.age = age # 'age' is an attribute
# Creating an instance of the 'Person' class
person1 = Person("Alice", 30)
# Accessing attributes
print(person1.name) # Output: Alice
print(person1.age) # Output: 30
What are and how to use public, protected and private attributes
In Python, attributes and methods can have different levels of visibility and
access control. The concepts of public, protected, and private attributes are used
to define how accessible these attributes should be from outside the class they
are defined in.
Public Attributes: Attributes without underscores are considered public and can
be accessed from anywhere, both within and outside the class.
class MyClass:
def __init__(self):
self.public_attr = "This is a public attribute"
obj = MyClass()
print(obj.public_attr) # Output: This is a public attribute
What are and how to use public, protected and private attributes
Protected Attributes: Attributes with a single underscore are considered
protected, These attributes are intended to be used as internal implementation
details and should not be accessed directly from outside the class.
class MyClass:
def __init__(self):
self._protected_attr = "This is a protected attribute"
obj = MyClass()
print(obj._protected_attr) # Output: This is a protected attribute (although
discouraged)
What are and how to use public, protected and private attributes
Private Attributes: Attributes with double underscores are considered private and
are intended to be used only within the class itself. Private attributes are not
accessible from outside the class.
class MyClass:
def __init__(self):
self.__private_attr = "This is a private attribute"
obj = MyClass()
# This will raise an AttributeError
# print(obj.__private_attr)
What is self
In Python, self is a conventionally used name for the first parameter of instance
methods in a class. It refers to the instance of the class itself.
Note for C++/Java/C# Programmers:
The self in Python is equivalent to the this pointer in C++ and the this reference
in Java and C#.
# Creating an instance
class MyClass:
obj = MyClass(42)
def __init__(self, value):
self.value = value
# Calling the method
obj.print_value() # Output: 42
def print_value(self):
print(self.value)
What is a method
A method is a function that is defined within a class in object-oriented
programming (OOP). Methods are used to define the behaviors or actions that
instances (objects) of a class can perform.
Definition: Methods are defined within a class using the same syntax as regular
functions, but they are indented under the class definition.
self Parameter: Instance methods in Python usually take the special self
parameter as their first parameter.
What is a method
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
# Creating an instance
rectangle = Rectangle(5, 3)
# Calling the method to calculate area
area = rectangle.calculate_area()
print("Area:", area) # Output: Area: 15
What is the special __init__ method and how to use it
The __init__ method is a special method in Python that is automatically called
when an instance of a class is created. It's also known as the "constructor"
method. The primary purpose of the __init__ method is to initialize the
attributes of the instance with the values passed as arguments during object
creation. This method allows you to set up the initial state of the object.
# Creating an instance of MyClass
obj = MyClass("value1", "value2")
class MyClass:
def __init__(self, arg1, arg2):
# Accessing the attributes of the instance
self.attribute1 = arg1
print(obj.attribute1) # Output: value1
self.attribute2 = arg2
print(obj.attribute2) # Output: value2
What is Data Abstraction, Data Encapsulation, and Information Hiding
Data abstraction is a concept in object-oriented programming that involves
presenting only the essential attributes and behaviors of an object while hiding
the unnecessary details.
For example, when you interact with a television remote control. you don't need
to know the intricate details of how the remote actually communicates with the
TV.
What is Data Abstraction, Data Encapsulation, and Information Hiding
Data encapsulation is the practice of bundling the data (attributes) and the
methods (functions) that operate on that data into a single unit called a class.
Information hiding is closely related to data encapsulation. It refers to the
practice of hiding the implementation details of a class and revealing only the
necessary interfaces to the outside world.
What is a property
In object-oriented programming, a property is a concept that allows you to
control access to an object's attributes by providing getter and setter methods.
Properties are used to ensure encapsulation and to define a controlled interface
for accessing and modifying an object's data.
properties are implemented using decorators and special methods, such as
@property, @<attribute>.setter, and @<attribute>.deleter.
problem
class BankAccount: class BankAccount:
def __init__(self, balance):
def __init__(self, balance): self._balance = balance # Use an underscore to indicate a
self.balance = balance "protected" attribute
@property
# Creating an instance def balance(self):
return self._balance
account = BankAccount(1000)
@balance.setter
# Risk:Directly modifying def balance(self, new_balance):
if new_balance < 0:
#the balance attribute raise ValueError("Balance cannot be negative.")
account.balance = -500 self._balance = new_balance
# This should not be allowed # Creating an instance
print(account.balance) account = BankAccount(1000)
# Using the property setter with validation
account.balance = -500 # This raises a ValueError
print(account.balance)
difference between an attribute and a property
class Person: class Temperature:
def __init__(self, celsius):
def __init__(self, name):
self._celsius = celsius
#'name' is an attribute
self.name = name @property
def celsius(self):
return self._celsius
person = Person("Alice")
# Accessing the attribute @celsius.setter
print(person.name) def celsius(self, value):
if value < -273.15:
raise ValueError("Temperature cannot be below absolute
zero.")
self._celsius = value
temp = Temperature(25)
print(temp.celsius) # Using the property
temp.celsius = 30 # Using the property setter
What is the Pythonic way to write getters and setters
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative.")
self._radius = value
@radius.deleter
def radius(self):
print("Circle radius deleted.")
del self._radius
# Creating an instance
circle = Circle(5)
# Using the property getter
print(circle.radius) # Output: 5
# Using the property setter
circle.radius = 8
print(circle.radius) # Output: 8
# Deleting the property using the deleter
del circle.radius # Output: Circle radius deleted.
How to dynamically create arbitrary new attributes for existing instances of a
class
you can dynamically create new attributes for existing instances of a class by
directly assigning values to attribute names that were not previously defined.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an instance
person = Person("Alice", 30)
# Dynamically adding new attributes
person.country = "Wonderland"
person.job = "Adventurer"
# Accessing the new attributes
print(person.country) # Output: Wonderland
print(person.job) # Output: Adventurer
How to bind attributes to object and classes
Binding Attributes to Objects (Instances): You can bind attributes to objects by
assigning values to them within the __init__ method or anywhere else within
the class methods.
class Person:
def __init__(self, name, age):
self.name = name # Binding attribute to the object
self.age = age
# Creating instances
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Accessing attributes of objects
print(person1.name) # Output: Alice
print(person2.age) # Output: 25
How to bind attributes to object and classes
Binding Attributes to Classes: You can bind class attributes outside of any
method, directly within the class body.
class Car:
# Class attribute
manufacturer = "Toyota"
def __init__(self, model):
self.model = model
# Creating instances
car1 = Car("Camry")
car2 = Car("Corolla")
# Accessing class attribute
print(car1.manufacturer) # Output: Toyota
print(car2.manufacturer) # Output: Toyota
# Accessing instance attribute
print(car1.model) # Output: Camry
print(car2.model) # Output: Corolla
What is the __dict__ of a class and/or instance of a class and what does it
contain
the __dict__ attribute is a dictionary that contains the attributes (both data and
methods) of a class or an instance of a class.
For a class: the __dict__ attribute holds the class attributes and methods defined
within the class. These are attributes that are shared among all instances of the
class. {
'__module__': '__main__',
class MyClass: 'class_attribute': 'This is a class attribute’,
'__init__': <function MyClass.__init__
class_attribute = "This is a class attribute" at 0x...>,
'__dict__': <attribute '__dict__' of
def __init__(self, instance_attribute): 'MyClass' objects>,
self.instance_attribute = instance_attribute '__weakref__': <attribute '__weakref__'
of 'MyClass' objects>, '__doc__': None
}
print(MyClass.__dict__)
How does Python find the attributes of an object or class
For an Instance: the __dict__ attribute holds the instance-specific attributes that
are assigned to the instance. It doesn't include the class attributes, as they are
shared among all instances.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
print(person.__dict__)
{'name': 'Alice', 'age': 30}
How to use the getattr function
The getattr() function in Python is used to dynamically retrieve an attribute from
an object or a class. It takes three arguments: the object (or class), the attribute
name as a string, and an optional default value (if the attribute is not found).
getattr(object, attribute_name, default_value)
How to use the getattr function
Getting an Attribute from an Object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
# Using getattr to get the 'name' attribute
name = getattr(person, "name")
print(name) # Output: Alice
How to use the getattr function
Getting an Attribute with a Default Value:
class Car:
def __init__(self, model):
self.model = model
car = Car("Camry")
# Using getattr with a default value
manufacturer = getattr(car, "manufacturer", "Unknown")
print(manufacturer) # Output: Unknown
How to use the getattr function
Getting an Attribute from a Class:
class Rectangle:
width = 0
height = 0
width_attribute = getattr(Rectangle, "width")
print(width_attribute) # Output: 0
04
Hands on lab Practice
Have a Question
Leave a Comment!
Subscribe
To stay updated with latest
videos
Share
To let the others know more
Thanks