Python 3 Deep Dive Part 4 Oop Patched 〈RECOMMENDED〉
class OptimizedNode: __slots__ = ['x', 'y'] def __init__(self, x, y): self.x = x self.y = y Use code with caution.
class BankAccount: def __init__(self, owner, balance): self.owner = owner self._balance = balance # Protected naming convention @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 Use code with caution. The Descriptor Protocol
In multiple inheritance, super() does not simply call the parent class. It finds the next class in the of the calling instance.
@celsius.setter def celsius(self, value): if value < -273.15: raise ValueError("Below absolute zero") self._celsius = value python 3 deep dive part 4 oop
class Book: def __init__(self, title, author, year): self._id = uuid.uuid4() self.title = title self.author = author self.year = year self._checked_out = False
When Lina first opened the heavy volume titled "Python 3 Deep Dive," a bookmark fell out with a single note: Part 4 — OOP. She smiled. The previous parts had taught her syntax, functions, and modules; now she stood at the door to object-oriented design.
In Python 3, encapsulation can be achieved using private variables and methods, which are denoted by a double underscore prefix. @celsius
class MetaExample(type): @classmethod def __prepare__(mcs, name, bases, **kwargs): print("Preparing namespace") return super().__prepare__(name, bases, **kwargs) def __new__(mcs, name, bases, namespace, **kwargs): print("Creating class") return super().__new__(mcs, name, bases, namespace)
class DatabaseConnection: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self, connection_string): # Warning: __init__ will still be called every time # unless handled explicitly. self.connection_string = connection_string Use code with caution. 2. Advanced Attribute Lookup and Descriptors
@property def checked_out(self): return self._checked_out In Python 3, encapsulation can be achieved using
Drawback:
Protocols are not enforced by the language but expected by the runtime.