Created
March 7, 2017 04:43
-
-
Save anonymous/121ae2e8b35529bc5f6bffa3484cbb2d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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