Thuộc tính

Lập trình hướng đối tượng trong Python

Alex Yarosh

Content Quality Analyst @ DataCamp

Thay đổi giá trị thuộc tính

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
Lập trình hướng đối tượng trong Python

Thay đổi giá trị thuộc tính

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

 

 

Kiểm soát truy cập thuộc tính?

  • kiểm tra tính hợp lệ của giá trị
  • hoặc đặt thuộc tính chỉ đọc
    • chỉnh set_salary() không ngăn emp.salary = -100
Lập trình hướng đối tượng trong Python

Thuộc tính bị hạn chế và chỉ đọc

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
Lập trình hướng đối tượng trong Python

@property

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

 

← Dùng thuộc tính “được bảo vệ” bắt đầu bằng _ để lưu dữ liệu

← Dùng @property trên phương thức có tên đúng bằng tên thuộc tính hạn chế; trả về thuộc tính nội bộ

← Dùng @attr.setter trên phương thức attr() sẽ được gọi khi obj.attr = value

  • giá trị gán được truyền làm đối số
Lập trình hướng đối tượng trong Python

@property

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
Lập trình hướng đối tượng trong Python

Vì sao dùng @property?

  $$\text{\Large{Với người dùng: hành xử như thuộc tính}}$$

 

$$\text{\Large{Với lập trình viên: kiểm soát truy cập}}$$

Lập trình hướng đối tượng trong Python

Các khả năng khác

→ Không thêm @attr.setter

Tạo thuộc tính chỉ đọc

→ Thêm @attr.getter

Dùng cho phương thức được gọi khi lấy giá trị của thuộc tính

→ Thêm @attr.deleter

Dùng cho phương thức được gọi khi xóa thuộc tính bằng del

Lập trình hướng đối tượng trong Python

Ayo berlatih!

Lập trình hướng đối tượng trong Python

Preparing Video For Download...