Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Getters, Setters, and Property Decorators | Encapsulation and Data Hiding
Python Object-Oriented Programming (OOP) Mastery

Getters, Setters, and Property Decorators

Swipe um das Menü anzuzeigen

123456789101112131415161718
class BankAccount: def __init__(self, balance): self._balance = balance @property def balance(self): return self._balance @balance.setter def balance(self, value): if value < 0: raise ValueError("Balance cannot be negative.") self._balance = value account = BankAccount(100) print(account.balance) # 100 account.balance = 200 print(account.balance) # 200

Property decorators in Python provide a way to control how attributes of a class are accessed and modified. In the BankAccount class, the balance attribute is managed using the @property decorator, which allows you to access balance as if it were a regular attribute, while actually using a method behind the scenes. The @balance.setter decorator lets you define a method that is called when you assign a new value to balance. This approach enables you to add logic, such as validation, whenever the attribute is set. This means you can keep the internal attribute (_balance) private, while exposing a controlled interface to users of the class.

1234567891011121314151617181920212223242526
class BankAccount: def __init__(self, balance): self._balance = balance @property def balance(self): return self._balance @balance.setter def balance(self, value): if not isinstance(value, (int, float)): raise TypeError("Balance must be a number.") if value < 0: raise ValueError("Balance cannot be negative.") self._balance = value account = BankAccount(50) try: account.balance = -10 # Raises ValueError except ValueError as e: print(e) # Output: Balance cannot be negative. try: account.balance = "fifty" # Raises TypeError except TypeError as e: print(e) # Output: Balance must be a number.

You should use property decorators when you need to encapsulate attribute access and enforce rules or validation on assignment. This is especially useful when you want to prevent invalid values, log changes, or trigger updates automatically when an attribute changes. Property decorators help you maintain a clean and intuitive interface, allowing users to work with attributes as usual, while you retain full control over how those attributes are managed internally.

question mark

Which of the following statements about property decorators in Python are true?

Wählen Sie alle richtigen Antworten aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 2

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 2. Kapitel 2
some-alt