Właściwości

Programowanie obiektowe w Pythonie

Alex Yarosh

Content Quality Analyst @ DataCamp

Zmiana wartości atrybutów

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
Programowanie obiektowe w Pythonie

Zmiana wartości atrybutów

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

 

 

Kontrola dostępu do atrybutów?

  • sprawdzanie poprawności wartości
  • lub uczynienie atrybutów tylko do odczytu
    • modyfikacja set_salary() nie zapobiega emp.salary = -100
Programowanie obiektowe w Pythonie

Atrybuty z ograniczeniami i tylko do odczytu

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
Programowanie obiektowe w Pythonie

@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

 

← Użyj atrybutu „chronionego" z przedrostkiem _ do przechowywania danych

← Użyj @property na metodzie o nazwie identycznej z nazwą atrybutu z ograniczeniami; zwróć wewnętrzny atrybut

← Użyj @attr.setter na metodzie attr(), która będzie wywoływana przy obj.attr = value

  • przypisywana wartość przekazywana jako argument
Programowanie obiektowe w Pythonie

@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
Programowanie obiektowe w Pythonie

Dlaczego używać @property?

  $$\text{\Large{Od strony użytkownika: zachowują się jak atrybuty}}$$

 

$$\text{\Large{Od strony dewelopera: kontrola dostępu}}$$

Programowanie obiektowe w Pythonie

Inne możliwości

→ Nie należy dodawać @attr.setter

Tworzy właściwość tylko do odczytu

→ Dodaj @attr.getter

Używane dla metody wywoływanej przy pobieraniu wartości właściwości

→ Dodaj @attr.deleter

Używane dla metody wywoływanej przy usuwaniu właściwości przez del

Programowanie obiektowe w Pythonie

Czas na ćwiczenia!

Programowanie obiektowe w Pythonie

Preparing Video For Download...