Skip to content

Instantly share code, notes, and snippets.

@bwangelme
Created January 5, 2017 13:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bwangelme/319b25c05c572bc2d7b002bf3f19d18d to your computer and use it in GitHub Desktop.
Save bwangelme/319b25c05c572bc2d7b002bf3f19d18d to your computer and use it in GitHub Desktop.
Metaclass 黑魔法
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
这个C元类的功能就是在准备类的命名空间的时候,
将其父类的非私有成员(不以_开头的成员)添加到
这个命名空间中,然后在创建这个类的时候,再把父类的非私有成员给删除掉。
"""
import os
class C(type):
@classmethod
def __prepare__(metacls, name, bases, **kwds):
d = dict()
for base in bases:
for key, value in base.__dict__.items():
if not key.startswith('_'):
d[key] = value
return d
def __new__(cls, name, bases, namespace, **kwds):
for base in bases:
for key, value in base.__dict__.items():
if not key.startswith('_'):
del namespace[key]
return type.__new__(cls, name, bases, dict(namespace))
class Config(metaclass=C):
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class DeployConfig(Config):
DATABASE = "time_log"
DATA_DIR = os.path.join(BASE_DIR, "data")
print(DeployConfig.__dict__)
print(DeployConfig.DATA_DIR)
"""
在这里,其实 DeployConfig 的命名空间中并没有 BASE_DIR ,
能够访问 BASE_DIR 是因为去访问它的父类的命名空间了。
"""
print(DeployConfig.BASE_DIR)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment