Skip to content

Instantly share code, notes, and snippets.

@nenetto
Created September 26, 2023 07:26
Show Gist options
  • Save nenetto/f1dbac6fd9dae06c17edc850a01e9497 to your computer and use it in GitHub Desktop.
Save nenetto/f1dbac6fd9dae06c17edc850a01e9497 to your computer and use it in GitHub Desktop.
Metaclasses Python
# 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