Fred Agbo
October 30, 2026
FiB4R
In the object-oriented model, the client is not supposed to muck-about with the object internals
The implementation should therefore provide methods to retrieve desired attributes (called getters) or to make changes to desired attributes (called setters)
Setting up getters and setters for the attribute
salary might look like:
def get_salary(self):
return self.salary
def set_salary(self, new_salary):
self.salary = new_salaryGetters are far more common than setters, as you don’t always want the client to have the freedom to change attributes on a whim
Printing out an object that you just created as an instance of a custom class will look ugly:
>>> C = Employee('Bob', 'clerk', 15)
>>> print(C)
<__main__.Employee object at 0x7f942ba13550>You can define special methods for a class that specify how your object should be converted to a string (or anything else really)
__str__ or
__repr__ method to specify how your object
might be printedclass Employee:
def __init__(self, name, title, salary):
self.name = name
self.title = title
self.salary = salary
def __str__(self):
return f"{self.name} ({self.title}): {self.salary}"
def get_salary(self):
return self.salary
def set_salary(self, new_salary):
self.salary = new_salary
self properly within our method
definitionsWhat would be the output of the last print statement in the code to the right?
class Demo:
def __init__(self):
self.x = []
def add(self, v):
self.x.append(v)
def get_x(self):
return self.x
A, B = Demo(), Demo()
C = B.get_x()
A.add(3)
B.add(3)
C.append(A)
print(A.get_x() == B.get_x())
What would be the output of the printed statement in the code to the right?
class Pet:
def __init__(self, name, color, age):
self.name = name
self.color="black"
self.age = age
def bmi(self, weight, height):
if weight/height > 2:
self.age = self.age*2
else:
self.age += 1
dog = Pet("Loly", "brown", 2)
dog.bmi(180,45)
print(f'{dog.name}, {dog.color}, {dog.age}')
BankAccount class with the
following requirements:
_account_number,
_balance,
_owner_name