Object-Oriented Programming in Python
Alex Yarosh
Content Quality Analyst @ DataCamp
class Employee: def set_name(self, name): self.name = name def set_salary(self, salary): self.salary = salary def give_raise(self, amount): self.salary = self.salary + amount
def __init__(self, name, salary): self.name, self.salary = name, salary
emp = Employee("Miriam Azari", 35000)
# Use dot syntax and = to alter atributes
emp.salary = emp.salary + 5000
class Employee: def set_name(self, name): self.name = name def set_salary(self, salary): self.salary = salary def give_raise(self, amount): self.salary = self.salary + amount
def __init__(self, name, salary): self.name, self.salary = name, salary
emp = Employee("Miriam Azari", 35000)
# Use dot syntax and = to alter atributes
emp.salary = emp.salary + 5000
set_salary()
wouldn't prevent emp.salary = -100
import pandas as pd
df = pd.DataFrame({"colA": [1,2], "colB":[3,4]})
df
colA colB
0 1 3
1 2 4
df.columns = ["new_colA", "new_colB"]
df
new_colA new_colB
0 1 3
1 2 4
# will cause an error
df.columns = ["new_colA", "new_colB", "extra"]
df
ValueError: Length mismatch:
Expected axis has 2 elements,
new values have 3 elements
df.shape = (43, 27)
df
AttributeError: can't set attribute
class Employer: def __init__(self, name, new_salary): self._salary = new_salary
@property def salary(self): return self._salary
@salary.setter def salary(self, new_salary):
if new_salary < 0: raise ValueError("Invalid salary") self._salary = new_salary
← Use "protected" attribute with leading _
to store data
← Use @property
on a method whose name is exactly the name of the restricted attribute; return the internal attribute
← Use @attr.setter
on a method attr()
that will be called on obj.attr = value
class Employer: def __init__(self, name, new_salary): self._salary = new_salary
@property def salary(self): return self._salary
@salary.setter def salary(self, new_salary): if new_salary < 0: raise ValueError("Invalid salary") self._salary = new_salary
emp = Employee("Miriam Azari", 35000)
# accessing the "property"
emp.salary
35000
emp.salary = 60000 # <-- @salary.setter
emp.salary = -1000
ValueError: Invalid salary
$$\text{\Large{User-facing: behave like attributes}}$$
$$\text{\Large{Developer-facing: give control of access}}$$
→ Do not add @attr.setter
Create a read-only property
→ Add @attr.getter
Use for the method that is called when the property's value is retrieved
→ Add @attr.deleter
Use for the method that is called when the property is deleted using del
Object-Oriented Programming in Python