Python 3.x Python:如何使用特定参数对函数进行别名?
我试图将函数指定为类属性,在类的不同实例中为函数指定特定参数。因此,如果我有两个实例Python 3.x Python:如何使用特定参数对函数进行别名?,python-3.x,function,parameters,Python 3.x,Function,Parameters,我试图将函数指定为类属性,在类的不同实例中为函数指定特定参数。因此,如果我有两个实例foo和bar,我希望foo.func()在调用时运行function(param1),在调用时运行bar.func() 我试过这样的方法: class Class: def __init__(self, func): self.func = func foo = Class(function(param1)) bar = Class(function(param2)) 但是当我运行
foo
和bar
,我希望foo.func()
在调用时运行function(param1)
,在调用时运行bar.func()
我试过这样的方法:
class Class:
def __init__(self, func):
self.func = func
foo = Class(function(param1))
bar = Class(function(param2))
但是当我运行它时,foo=Class(function(param1))
语句只是执行function(param1)
,而不是创建类的新实例。如果我尝试单独为函数别名,也会出现同样的问题,例如:
alias_func = function(param1)
foo = Class(alias_func)
有没有办法做到这一点?我真的不想为类的每个实例定义一个新函数,但我在搜索中没有找到任何关于它的内容。提前谢谢大家 您可以正常使用:
from functools import partial
class MyClass:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
abc = partial(MyClass, 'a', 'b', 'c')
test1 = abc()
test2 = abc()
print(test1.x) # prints a
assert test1 is not test2 # Make sure abc is producing different objects
您始终可以制作包装:
class my_class:
def __init__(self, *, before=[], after=[], named={}):
self.before = before
self.after = after
self.named = named
def wrap(self, fn, *args, **kwargs):
lmerge=self.before + list(args) + self.after
dmerge=self.named.copy()
dmerge.update(kwargs)
return fn(*lmerge, **dmerge)
w1=my_class(before=["before", "more"], after=["after"])
w2=my_class(before=["before"], after=["after"], named={'sep':"..."})
w1.wrap(print, "hi")
w1.wrap(print, "yo", sep="-")
w2.wrap(print, "itadakimasu")
w2.wrap(print, "hasta", "siempre", sep="-")
w3=my_class(named={'before':["more"]})
w4=w3.wrap(my_class, after=["less"])
w4.wrap(print, "zboing")
听起来你可能在找@PatrickHaugh这正是我要找的,谢谢!你能马上知道类是否有一个等价物,用特定的参数生成实例吗?你能更具体一点吗?你是想让一个类有一个部分函数作为属性,还是想让一个部分函数可以生成对象?我想是第二个。例如,我想分配var=Class(x=1,y=2,z=3),然后使用“instance=var”而不是“instance=Class(x=1,y=2,z=3)”创建一个实例