a single class with a shared lookup-table that defines the shared info

5025 ワード

100+ almost identical classes is crazy. Classes are organizational structures. Having dozens of them with almost no variation does't seem useful. It's over-specialization.
It sounds very much like you need a single class with a shared lookup-table that defines the shared info. Something like:
from collections import namedtuple Lang= namedtuple('Lang','style points creator') LANG_FORM ={'Python':Lang('dynamic',84,'Guido van Rossum'),'Java':Lang('static',65,'James Gosling'),# ...'Pascal':Lang('static',33,'Niklaus Wirth')}classProtean(object):def __init__(self, name, form): self.name = name self.form = form self.lang = LANG_FORM[form]# optional# methods here

Here LANG_FORM can be a global variable (quasi-constant), or it could be a class variable. Either way, each instance gets basically just a pointer back to its shared info (what you refer to as class variables). It doesn't even strictly need that, if you're willing to index LANG_FORM whenever you need it, rather than memorizing it in each instance.
If you want to have each of the instances depict itself based on its form/kind/quasi-class, add a __repr__ method:
def __repr__(self): classname = self.__class__.__name__ return"{0}-{1}({2!r}, {3})".format(classname, self.form, self.name, self.lang.points)

Then:
p =Protean('CPython','Python')print p

Yields:
Protean-Python('CPython',84)

 
from: http://programmers.stackexchange.com/questions/253612/one-boilerplate-class-or-many-similar-classes