Zero to Py by Michael Green

Zero to Py by Michael Green

Author:Michael Green [Michael Green]
Language: eng
Format: epub
Publisher: leanpub.com
Published: 2023-02-20T00:00:00+00:00


Metaclasses can also be used to enforce from the library constraints or expectations on user code. Consider another example where a library expects users to define certain methods on a derived classes. You can use a metaclass to catch type errors at the class instantiation, instead of later during runtime.

1 >>> class LibraryMetaclass(type): 2 ... def __new__(cls, name, bases, attrs): 3 ... if "my_method" not in attrs: 4 ... raise AttributeError( 5 ... "derived class must define method my_method()" 6 ... ) 7 ... return type.__new__(cls, name, bases, attrs) 8 ... 9 >>> class BaseClass(metaclass=LibraryMetaclass): 10 ... my_method = None 11 ... 12 >>> class DerivedClass(BaseClass): 13 ... def my_method(self): 14 ... pass 15 ... 16 >>> class BadClass(BaseClass): 17 ... pass 18 Traceback (most recent call last): 19 File "<stdin>", line 1, in <module> 20 File "<stdin>", line 4, in __new__ 21 AttributeError: derived class must define method my_method()



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.