pythonbeginner
Descriptor
Advanced Python pattern: descriptor
pythonPress ⌘/Ctrl + Shift + C to copy
class Positive:
def __set_name__(self, owner, name):
self.name = '_' + name
def __get__(self, obj, objtype=None):
return getattr(obj, self.name)
def __set__(self, obj, value):
if value <= 0:
raise ValueError('must be positive')
setattr(obj, self.name, value)
class Product:
price = Positive()
def __init__(self, price: int):
self.price = price
p = Product(10)
print(p.price)Use Cases
- advanced programming
- patterns
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
Type Hints
Advanced Python pattern: type-hints
Best for: advanced programming
#python#advanced
pythonintermediate
Dataclass
Advanced Python pattern: dataclass
Best for: advanced programming
#python#advanced
pythonadvanced
Abc Abstract
Advanced Python pattern: abc-abstract
Best for: advanced programming
#python#advanced
pythonbeginner
Enum Types
Advanced Python pattern: enum-types
Best for: advanced programming
#python#advanced