Last active
September 13, 2015 02:22
-
-
Save c-bata/e148cadcfd2aa5ceb559 to your computer and use it in GitHub Desktop.
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
import itertools | |
class _BaseValidator(object): | |
_counter = itertools.count() | |
def __new__(cls, *args, **kw): | |
validator = object.__new__(cls) | |
validator._order = next(cls._counter) | |
return validator | |
class _ValidatorMeta(type): | |
validators = [] | |
def __init__(cls, name, bases, clsattrs): | |
for name, value in clsattrs.items(): | |
if isinstance(value, _BaseValidator): | |
delattr(cls, name) | |
if not value.name: | |
value.name = name | |
cls.validators.append((value._order, value)) | |
cls.validators.sort() | |
BaseValidator = _ValidatorMeta( | |
'BaseValidator', | |
(_BaseValidator,), | |
{} | |
) | |
class SampleDataFrame(object): | |
id = BaseValidator() | |
name = BaseValidator() | |
age = BaseValidator() | |
if __name__ == '__main__': | |
hoge = SampleDataFrame() | |
print("id: ", hoge.id._order) | |
print("name: ", hoge.name._order) | |
print("age: ", hoge.age._order) | |
# $ python3 metaclasses_sample.py | |
# id: 0 | |
# name: 1 | |
# age: 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment