Define class attribute
class Human: species = "H. sapiens"
WARNING - when using mutable types, single instance is shared by all the objects!
Define instance attribute
def \_\_init\_\_(self, name):
self.name = nameDefine private instance attribute
def \_\_init\_\_(self, name):
# Private (_ is only suggestion, not enforced in any way)
self._age = 0
# Private (\_\_ triggers name mangling, field is renamed to _Human\_\_update to prevent collisions in child classes)
self.\_\_update(iterable)Define instance method
def say(self, msg):
return msgDefine class method
@classmethod
def get_species(cls):
return cls.speciesDefine static method
@staticmethod
def grunt():
return "*grunt*"Define Getter, setter and deleter called age
# Getter (access by obj.age)
@property
def age(self):
return self._age
# Setter
@age.setter
def age(self, age):
self._age = age
# Deleter
@age.deleter
def age(self):
del self._ageConstruct new object of Human class
i = Human(name="Ian")
Define struct (POCO) class in python
from dataclasses import dataclass
@dataclass
class Employee:
name: str
dept: str
salary: intInitialize parent from derived class ctor
super().\_\_init\_\_(name)
Check if sup is instance of class Human
isinstance(sup, Human);
Check if sup is derived from Human
issubclass(sup, Human);
Check type of sup
type(sup);
Define class Superhero that derives from Human
class Superhero(Human): pass
Define class Superhero that derives from Human and Bat
class Batman(Superhero, Bat): pass
Get the order in which classes are searched for an attribute or method.
What is the full name of that property?
Batman.\_\_mro\_\_
Method Resolution Order
Define class as iterator
class Reverse:
# Called by iter()
def \_\_iter\_\_(self):
return self
# Iterator must have a next method
def \_\_next\_\_(self):
if self.index == 0:
raise StopIteration
return data;Make hashable dataclass (that can be used as map key for example)
@dataclass(frozen=True) class ServerConfig: host: str port: int = 8080
What are benefits of dataclass over reguklar class for simple structures
Can have order / be readonly
@dataclass(order=True, frozen=True)
Auto-generated \_\_repr\_\_
print(config) # Output: ServerConfig(host='localhost', port=8080, active_plugins=['auth', 'cache'])
Easy conversion to dict (great for serialization)
print(asdict(config))
Built-in equality check (compares values, not identity)
assert config == ServerConfig("localhost", active_plugins=["auth", "cache"])What are slots in class, when and how to use them?
\_\_slots\_\_ is a class-level optimization that tells Python to not use a dynamic \_\_dict\_\_ for instance attributes.```python
class SlottedClass:
# Explicitly declare which attributes this class can have
__slots__ = (‘x’, ‘y’)
def __init__(self, x, y):
self.x = x
self.y = y
obj = SlottedClass(10, 20)
obj.z = 99 # AttributeError: ‘SlottedClass’ object has no attribute ‘z’
~~~
What are trade-off and gotachas of using slots in class?
\_\_dict\_\_ to slots).B inherits from slotted class A but doesn’t define \_\_slots\_\_ itself, B will have a \_\_dict\_\_.\_\_slots\_\_ (layout conflict).