我想创建一个类,其中实例根据其变量具有不同的方法。
例如:
class Spam:
def __init__(self, eggs):
self.eggs = eggs
然后,如果 Spam
的 self.eggs
为 5,则它的 foo
定义应如下所示:
def foo(self):
print(self.eggs)
否则
def foo(self, excited):
if excited:
print("{}!!!!!".format(self.eggs))
else:
print("{}...".format(self.eggs))
目前,我通过在类外部声明两个 foo
函数(具有不同名称),并在 __init__
中设置实例的方法来实现这一点。但是,这会从类定义中删除函数定义,这是我真正不想做的。还有其他方法吗?
编辑:实际上下文。
我正在创建一些类来表示图中的节点,其中每个图都可以加权或不加权。
我希望节点有一个 link
方法,将另一个节点作为参数,将它们连接在一起。加权图中的节点(即那些 self.graph.weighted
为 True
的节点)应该有一个 link
方法,其中另一个参数指定权重连接边。有更好的方法吗?例如,将权重参数设置为可选,但存在于所有节点的 link
方法中。
最佳答案
扩展一下 jme 提到的内容:
默认参数方法:
class Node:
def __init__(self, name):
self.name = name
self.links = []
def link(self, other, weight = None):
self.links.append((other, weight))
继承方法:
class Node:
def __init__(self, name):
self.name = name
self.links = []
def link(self, other):
#one of the following, depending if other methods of this base class will be used in the derived class
self.links.append((other, None))
#self.links.append(other)
class WeightedNode(Node):
def link(self, other, weight):
self.links.append((other, weight))
关于python - 根据实例变量为类实例提供不同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22233149/