基本上,我想创建一个“模板”类型的对象,其中包含 staticmethods
。然后创建一个继承自该对象的新对象,但使用父对象的方法,使用 functools.partial
,其中使用子对象的参数。子对象的参数与父对象方法的参数具有相同的名称。结果范式将类似于以下内容:
class Naked:
@staticmethod
def echo1(foo):
return f"echo1: {foo}"
@staticmethod
def echo2(bar, bla):
return f"echo2: {bar}, {bla}"
class Clothed(Naked):
def __init__(self, *args, **kwargs):
for arg in args:
setattr(self, arg, arg)
for k,v in kwargs.items():
setattr(self, k, v)
a = Clothed(foo = "Hello", bar = "World")
a.echo1 == "echo1: Hello"
a.echo2("wsup?") == "echo2: World, wsup?"
以下是一个不起作用的尝试:
from inspect import signature
from functools import partial
class Meta(type):
def __init__(cls, name, bases, attrs):
funcs = (k for k,v in attrs.items() if callable(v) and k not in dir(type)) #this doesn't work...
for func in funcs:
args = signature(func).keys() #function argument names
newargs = {arg:getattr(self, arg, None) for arg in args} #create dictionary with val from instance, how is this possible, no self here?
attrs[func] = partial(func,newargs)
return type.__init__(cls, name, bases, attrs)
class Naked(metaclass=Meta):
@staticmethod
def echo1(foo):
return f"echo1: {foo}"
@staticmethod
def echo2(bar, bla):
return f"echo2: {bar}, {bla}"
class Clothed(Naked):
def __init__(self, *args, **kwargs):
for arg in args:
setattr(self, arg, arg)
for k,v in kwargs.items():
setattr(self, k, v)
__init__
中的attrs
参数是一个字典,那么你的if callable(attr)
似乎是在检查attr键是否可调用。键是字符串,所以它不可调用,对吧?也许if callable(attrs[attr])
可以工作? - Håken Lid