python - 根据实例变量为类实例提供不同的方法

标签 python class

我想创建一个类,其中实例根据其变量具有不同的方法。

例如:

class Spam:
    def __init__(self, eggs):
        self.eggs = eggs

然后,如果 Spamself.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.weightedTrue 的节点)应该有一个 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/

相关文章:

python - 匹配列表中的项目 - Python

C++ 'class' 类型重定义

python 类更改另一个类。为什么?

c++ - 头文件中的类声明和静态变量

java - Java嵌套静态类

c++ - 如何在 C++ 类中使用 JNI registerNatives?

python - Matplotlib 动画 : how to dynamically extend x limits?

python - Elasticsearch-python批量帮助程序API上没有filter_path选项

Python jaeger-client 跟踪器不报告重用

python - cryptopp 错误 : expected '=' , ',' 、 ';' 、 'asm' 或 '__attribute__' 在 '{' token 之前