Last active
December 5, 2019 10:15
-
-
Save fujimisakari/6b9ea4e50bf53c353bc4 to your computer and use it in GitHub Desktop.
Pythonでメタプログラミング ref: https://qiita.com/fujimisakari/items/0d4786dd9ddeed4eb702
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
class Hoge(object): | |
def function1(self, args): | |
return args | |
def function2(self, args): | |
return args + 50 |
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
def func1(self, args): | |
return args | |
def func2(self, args): | |
return args + 50 | |
# type(クラス名、親クラス、メンバー属性)になります | |
Hoge = type('Hoge', (object, ), {'function1': func1, 'function2': func2}) |
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
class HogeMeta(type): | |
def __new__(mcs, name, bases, dictionary): | |
cls = type.__new__(mcs, name, bases, dictionary) | |
setattr(cls, 'member1', 10) | |
setattr(cls, 'member2', 20) | |
return cls | |
class Hoge(object): | |
__metaclass__ = HogeMeta | |
print Hoge().member1 -> 10 | |
print Hoge().member2 -> 20 | |
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
class AttackSkill(object): | |
name = u'特大攻撃' | |
class HealSkill(object): | |
name = u'回復' | |
class PoisonSkill(object): | |
name = u'毒攻撃' | |
class SkillMeta(type): | |
def __new__(mcs, name, bases, dictionary): | |
cls = type.__new__(mcs, name, bases, dictionary) | |
skills = {'attack': AttackSkill, | |
'heal': HealSkill, | |
'poison': PoisonSkill} | |
cls.SKILLS = skills | |
return cls | |
class Skills(object): | |
__metaclass__ = SkillMeta | |
SKILLS = {} | |
@classmethod | |
def get(cls, skill_key): | |
return cls.SKILLS[skill_key] | |
Skill = Skills.get | |
print Skill('attack').name -> 特大攻撃 | |
print Skill('heal').name -> 回復 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment