Skip to content

Instantly share code, notes, and snippets.

@fujimisakari
Last active December 5, 2019 10:15
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 fujimisakari/6b9ea4e50bf53c353bc4 to your computer and use it in GitHub Desktop.
Save fujimisakari/6b9ea4e50bf53c353bc4 to your computer and use it in GitHub Desktop.
Pythonでメタプログラミング ref: https://qiita.com/fujimisakari/items/0d4786dd9ddeed4eb702
class Hoge(object):
def function1(self, args):
return args
def function2(self, args):
return args + 50
def func1(self, args):
return args
def func2(self, args):
return args + 50
# type(クラス名、親クラス、メンバー属性)になります
Hoge = type('Hoge', (object, ), {'function1': func1, 'function2': func2})
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
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