自动生成的Python构造函数 [英] Automatically-generated Python constructor
问题描述
我从SQLAlchemy(以及Pygame的几个项目)的多个项目中获得了无数的Python类,最近我注意到其中许多模式:它们的构造函数总是这样:
I have countless Python classes from various projects from SQLAlchemy (and a couple from Pygame as well), and I recently noticed a pattern in many of them: their constructors always went something like this:
class Foo(Base):
def __init__(self, first, last, email, mi=""):
self.first = first
self.last = last
self.email = email
self.mi = mi
...因此,构造函数所做的唯一一件事就是将一组位置参数转移到一个完全相同名称的数据成员集中,而不执行任何计算或其他函数调用。
... whereby the only thing the constructor did was to transfer a set of positional arguments into an exactly identically named set of data members, performing no calculation or other function calls whatsoever.
在我看来,这种重复是不必要的,并且在更改时容易出现人为错误。
It seems to me that this repetition is unnecessary and prone to human error upon change.
这使我想到这里的问题:是否有可能自动生成这样的 __ init __(self,...)
函数,最好不要弄乱CPython字节码或使用模板es / macros来更改源文件本身?
This leads me to the question here: is it possible to automatically generate such an __init__(self, ...)
function, preferably without mucking around with CPython bytecode or using templates/macros to alter the source file itself?
推荐答案
您可能可以使用元类来做到这一点。这是一个覆盖 __ init __()
的元类的示例:
Python类装饰器
You can probably do this with Metaclasses. Here's an example of a metaclass which overrides __init__()
:
Python Class Decorator
当然,您需要以某种方式指定字段/自变量名称-或使用命名的自变量(如果愿意)。这是一种方法:
You will need to somehow specify the field/argument names, of course - or used named arguments, if you prefer. Here's one way to do that:
# This is the mataclass-defined __init__
def auto_init(self, *args, **kwargs):
for arg_val, arg_name in zip(args, self.init_args):
setattr(self, arg_name, arg_val)
# This would allow the user to explicitly specify field values with named arguments
self.__dict__.update(kwargs)
class MetaBase(type):
def __new__(cls, name, bases, attrs):
attrs['__init__'] = auto_init
return super(MetaBase, cls).__new__(cls, name, bases, attrs)
class Base(object):
__metaclass__ = MetaBase
# No need to define __init__
class Foo(Base):
init_args = ['first', 'last', 'email', 'mi']
这篇关于自动生成的Python构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!