【发布时间】:2019-01-04 14:01:08
【问题描述】:
我正在尝试将函数绑定到对象实例。例如,我有一个对象,我试图将一个函数绑定到条件属性。 问题是我想使用装饰器来做到这一点:
class Transition(object):
def __init__(self, enter, exit, condition=None):
if not isinstance(enter, State) or not isinstance(exit, State):
raise TypeError("Parameters should be an instance of the State class")
self.enter = enter
self.exit = exit
self.condition = None
self.effect = None
def __repr__(self):
print("Going from {} to {} with condition {} and effect {}".format(self.enter, self.exit, self.condition.__name__, self.effect.__name__))
def __eq__(self, other):
return self.enter == other.enter and self.exit == other.exit
def is_enpoint(self, endpoints):
"""
:parameter --> 'endpoints' is a tuple indicating where the transition flows(from, to)
:return --> boolean
:description --> check if the given endpoints are valid
"""
return self.enter == endpoints[0] and self.exit == endpoints[1]
然后我将一个函数绑定到对象的实例。
@bind
my_condition():
return True
在此之后,如果我们查看对象的实例条件属性
,我们应该有对给定函数的引用编辑 1:
f = Transition()
f1 = Transition()
@bind(f)
def condition1():
return True
@bind(f1)
def condition2():
return False
f 实例应该引用 condition1 函数,f2 实例应该引用 condition 属性的 condition2
【问题讨论】:
-
不清楚您的问题是什么...您希望所有其他对象正常查找其属性,但一个特定对象应该使用属性/函数吗?你为什么要使用装饰器语法呢?你想把这个函数作为一个方法放在那个类中吗?你如何定义它是哪个属性?
-
欢迎来到 SO。恐怕您的问题并不是真正的问题-您说明了您想做什么,但没有解释您的实际问题是什么。请注意,如果问题是“如何做到这一点”,您应该首先自己尝试。
-
@brunodesthuilliers 我做到了。我也在网上搜索了答案,但没有找到。
-
@AlexandreManeta“你做了”什么?解释你的实际问题?对不起,但你没有 - 你的帖子绝对没有提到你为实现你的功能做了什么,也没有提到你遇到了什么问题。您可能想阅读帮助部分,特别是这个:stackoverflow.com/help/how-to-ask 和这个:stackoverflow.com/help/on-topic
标签: python python-3.x decorator