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

本文探讨了在编程中处理大量几乎相同类的策略,建议使用单个类结合共享查找表来定义共通信息。通过实例演示如何实现类变量与共享信息的有效利用,以减少重复代码并提高代码复用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值