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

2B Creating Classes in Python

Uploaded by

asifjoy.phy.bd
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)
3 views7 pages

2B Creating Classes in Python

Uploaded by

asifjoy.phy.bd
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
You are on page 1/ 7

Python Object and Classes

Updated on Jan 07, 2020


https://thepythonguru.com/python-object-and-classes/

Creating object and classes


Python is an object-oriented language. In Python everything is object i.e. int, str, bool
even modules, functions are also objects.

Object oriented programming use objects to create programs, and these objects
stores data and behaviors.

Defining class
Class name in Python is preceded with class keyword followed by a colon (:). Classes
commonly contains data field to store the data and methods for defining behaviors.
Also, every class in Python contains a special method called initializer (also
commonly known as constructors), which get invoked automatically every time new
object is created.

Let's see an example.

1 class Person:
2
3 # constructor or initializer
4 def __init__(self, name):
5 self.name = name # name is data field also known as instance variables
6
7 # method which returns a string
8 def whoami(self):
9 return "You are " + self.name

Here we have created a class called Person which contains one data field called name
and method whoami().

What is self?
All methods in Python including some special methods like initializer have first
parameter self. This parameter refers to the object which invokes the method.
When you create new object the self parameter in the __init__ method is
automatically set to reference the object you have just created.

Creating object from class


1 p1 = Person('tom') # now we have created a new person object p1
2 print(p1.whoami())
3 print(p1.name)

Expected Output:

You are tom


tom

Note:
When you call a method, you don't need to pass anything to self parameter,
Python automatically does that for you behind the scenes.

You can also change the name data field.

1 p1.name = 'jerry'
2 print(p1.name)

Expected Output:

jerry

Although it is a bad practice to give access to your data fields outside the class. We
will discuss how to prevent this next.

Hiding data fields


To hide data fields you need to define private data fields. In Python you can create
private data field using two leading underscores. You can also define a private
method using two leading underscores.
Let's see an example

1 class BankAccount:
2
3 # constructor or initializer
4 def __init__(self, name, money):
5 self.__name = name
6 self.__balance = money # __balance is private now, so it is only
7 # accessible inside the class
8
9 def deposit(self, money):
10 self.__balance += money
11
12 def withdraw(self, money):
13 if self.__balance > money :
14 self.__balance -= money
15 return money
16 else:
17 return "Insufficient funds"
18
19 def checkbalance(self):
20 return self.__balance
21
22 b1 = BankAccount('tim', 400)
23 print(b1.withdraw(500))
24 b1.deposit(500)
25 print(b1.checkbalance())
26 print(b1.withdraw(800))
27 print(b1.checkbalance())

Expected Output:

Insufficient funds
900
800
100

Let's try to access __balance data field outside of class.

print(b1.__balance)

Expected Output:

AttributeError: 'BankAccount' object has no attribute '__balance'

As you can see, now the __balance field is not accessible outside the class.

This technique is called attribute mangling. (read additional information below,


from a different source)

Attribute Mangling
In Python, attribute mangling is a technique used to protect class attributes from
being accidentally overridden by subclasses. It does this by modifying the
attribute's name in a specific way, making it less likely to collide with names in
subclasses.

How it works:
• Double underscores: Any attribute or method name that starts with double
underscores (__) and does not end with double underscores is mangled.

• Mangling process: Python renames the attribute by prefixing it with the class
name. For example, an attribute named __my_attr in a class MyClass becomes
_MyClass__my_attr.

Example:
class MyClass:
def __init__(self):
self.__private_var = 10
def print_var(self):
print(self.__private_var)

obj = MyClass()
obj.print_var() # Output: 10

# Trying to access the mangled attribute directly


print(obj.__private_var) # This will raise an AttributeError

# Accessing the mangled attribute using its mangled name


print(obj._MyClass__private_var) # Output: 10

Purpose:
• Encapsulation: While Python doesn't have strict access modifiers like Java or C++,
mangling provides a way to create "private" attributes. This discourages direct
access from outside the class and helps prevent unintended modification.
• Avoiding name clashes in subclasses: Mangling ensures that attribute names in a
subclass don't accidentally clash with attributes in the parent class.

Key points:
• Mangling is not a security feature. It's just a way to avoid accidental name collisions.
• You can still access mangled attributes if you know the mangled name, but it's
considered bad practice.
• Single leading underscores (_) are a convention indicating that an attribute is
intended for internal use within the class or module. It doesn't trigger mangling.
Applying Encapsulation In Python
Adapted from: https://python-course.eu/oop/object-oriented-programming.php
Original text by Bernd Klein. Last modified: 01 Feb 2022

Encapsulation is often accomplished by providing two kinds of methods for


attributes: The methods for retrieving or accessing the values of attributes are
called getter methods (also known as 'accessors'). Getter methods do not change
the values of attributes, they just return the values. The methods used for changing
the values of attributes are called setter methods (also known as 'mutators').

We will define now a Robot class with two getters and two setters for the name and
build_year attributes. We will call them get_name and set_name, get_build_year and
set_build_year accordingly.

1 class Robot:
2 def __init__(self, name = None, build_year = None):
3 self.__name = name
4 self.__build_year = build_year
5
6 def say_hi(self):
7 if self.__name:
8 print("Hi, I am " + self.__name)
9 else:
10 print("Hi, I am a robot without a name")
11 if self.__build_year:
12 print("I was built in " + str(self.__build_year))
13 else:
14 print("It's not known, when I was created!")
15
16 def set_name(self, name):
17 self.__name = name
18
19 def get_name(self):
20 return self.__name
21
22 def set_build_year(self, year):
23 self.__build_year = year
24
25 def get_build_year(self):
26 return self.__build_year
27
28
29 x = Robot("Henry", 2008)
30 y = Robot()
31 y.set_name("Marvin")
32 x.say_hi()
33 y.say_hi()

Expected Output:

Hi, I am Henry
I was built in 2008
Hi, I am Marvin
It's not known, when I was created!

You might also like