Skip to content

Instantly share code, notes, and snippets.

@nenodias
Forked from anonymous/MetaClass.py
Created March 7, 2017 16:30
Show Gist options
  • Save nenodias/a386ea6f2f58c5ad77883d9efdc544e3 to your computer and use it in GitHub Desktop.
Save nenodias/a386ea6f2f58c5ad77883d9efdc544e3 to your computer and use it in GitHub Desktop.
from abc import ABCMeta
from abc import abstractmethod
class LowerMeta(type):
"""Metaclass thats change the attr and method to be used
with lowercase"""
def __new__(lowerattr_Metaclass, future_ClassName,
future_ClassParents, future_ClassAttr):
lowercase_attr = {}
for name, val in future_ClassAttr.items():
if not name.startswith("__"):
lowercase_attr[name.lower()] = val
else:
lowercase_attr[name] = val
return type(future_ClassName, future_ClassParents,
lowercase_attr)
class Foo(metaclass=LowerMeta): # define metaclass in python3^
C = 10
def ABC(self):
return 3
# foo = Foo()
# print(foo.abc()) # if you call the method with upper case will not work
class DocMeta(type):
def __init__(self, name, bases, attrs):
for key, value in attrs.items():
# skip special/private methods.
if key.startswith("__"): continue
# skip any non-callable.
if not hasattr(value, "__call__"): continue
# check for a doc string.
if not getattr(value, "__doc__"):
raise TypeError("{} must to havea docstring".format(key))
type.__init__(self, name, bases, attrs)
class Door(metaclass=DocMeta):
def __init__(self, number, status):
self.number = number
self.status = status
def open(self):
''' now the method must have a docstring'''
self.status = "open"
def close(self):
''' now the method must have a docstring'''
self.status = "closed"
# door = Door(1, 'open')
# print(door.status)
class Car(metaclass=ABCMeta):
"""Another metaclass that you can not instantiate
just Inherit. or will raise a TypeError
TypeError: Can't instantiate abstract class Car with
abstract methods chage_gear, start_engine"""
def __init__(self, carName, carModel, carColor):
self.carName = carName
self.carModel = carModel
self.carColor = carColor
@abstractmethod
def chage_gear(self):
pass
@abstractmethod
def start_engine(self):
pass
car = Car('Uno', 'Volks', 'White')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment