-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdvanced classes descriptors.py
More file actions
42 lines (33 loc) · 1.08 KB
/
Copy pathAdvanced classes descriptors.py
File metadata and controls
42 lines (33 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class PriceControl:
"""
Descriptor which don't allow to set price
less than 0 and more than 100 included.
"""
def __get__(self, instance, owner):
return instance.__dict__[self.name]
def __set__(self, instance, value):
if (value < 0) or (value > 100):
raise ValueError
instance.__dict__[self.name] = value
def __set_name__(self, owner, name):
self.name = name
class NameControl:
"""
Descriptor which don't allow to change field value after initialization.
"""
def __get__(self, instance, owner):
return instance.__dict__[self.name]
def __set__(self, instance, value):
if (self.name in instance.__dict__):
raise ValueError
instance.__dict__[self.name] = value
def __set_name__(self, owner, name):
self.name = name
class Book:
author = NameControl()
name = NameControl()
price = PriceControl()
def __init__(self, author, name, price) -> None:
self.author = author
self.name = name
self.price = price