Last active
May 24, 2024 21:10
-
-
Save Opalo/6113324d994578c4f5a7c9b1f02d2faf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DataDescriptor: | |
def __init__(self, name): | |
self.name = name | |
def __get__(self, obj, objtype=None): | |
if obj: | |
return obj.__dict__[self.name] | |
else: | |
return self | |
def __set__(self, obj, value): | |
obj.__dict__[self.name] = value | |
class Queryable(type): | |
def __new__(cls, name, bases, attrs): | |
for k, v in attrs.items(): | |
if isinstance(v, DataDescriptor): | |
v.name = k | |
result = type.__new__(cls, name, bases, dict(attrs)) | |
return result | |
class Order(metaclass=Queryable): | |
item_count = DataDescriptor() | |
cost = DataDescriptor() | |
if __name__ == '__main__': | |
print(Order.__dict__) | |
# Run gives: | |
# Traceback (most recent call last): | |
# File "hatchd.py", line 31, in <module> | |
# class Order: | |
# File "hatchd.py", line 32, in Order | |
# item_count = DataDescriptor() | |
# TypeError: __init__() missing 1 required positional argument: 'name' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment