Created
September 26, 2023 07:26
-
-
Save nenetto/f1dbac6fd9dae06c17edc850a01e9497 to your computer and use it in GitHub Desktop.
Metaclasses Python
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
# Rarely used, metaclasses can be used for validation of other classes | |
class ValidatePolygon(type): | |
def __new__(meta, name, bases, class_dict): | |
# Don’t validate the abstract Polygon class | |
if bases != (object,): | |
if class_dict[‘sides’] < 3: | |
raise ValueError(‘Polygons need 3+ sides’) | |
return type.__new__(meta, name, bases, class_dict) | |
class Polygon(object, metaclass=ValidatePolygon): | |
sides = None # Specified by subclasses | |
@classmethod | |
def interior_angles(cls): | |
return (cls.sides - 2) * 180 | |
class Triangle(Polygon): | |
sides = 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment