相关疑难解决方法(0)

将方法动态附加到使用swig生成的现有Python对象?

我正在使用Python类,并且我没有对其声明的写入权限.如何__str__在不修改类声明的情况下将自定义方法(如)附加到从该类创建的对象中?

编辑:谢谢你的所有答案.我尝试了所有这些,但他们没有解决我的问题.这是一个最小的例子,我希望能澄清这个问题.我使用swig来包装C++类,目的是覆盖swig模块返回的对象__str__功能.我使用cmake来构建示例:

test.py

import example

ex = example.generate_example(2)

def prnt(self):
    return str(self.x)

#How can I replace the __str__ function of object ex with prnt?
print ex
print prnt(ex)
Run Code Online (Sandbox Code Playgroud)

example.hpp

struct example
{
    int x;
};

example generate_example(int x);
Run Code Online (Sandbox Code Playgroud)

example.cpp

#include "example.hpp"
#include <iostream>

example generate_example(int x)
{
    example ex;
    ex.x = x;
    return ex;
}

int main()
{
    example ex = generate_example(2);
    std::cout << ex.x << "\n";
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

example.i

%module example

%{ …
Run Code Online (Sandbox Code Playgroud)

python methods class dynamic

9
推荐指数
1
解决办法
4084
查看次数

InvalidArgumentError:节点具有来自不同帧的输入

我正在玩Tensorflow并遇到这个代码的问题:

def process_tree_tf(matrix, weights, idxs, name=None):

    with tf.name_scope(name, "process_tree", [tree, weights, idxs]).as scope():
         loop_index = tf.sub(tf.shape(matrix)[0], 1)
         loop_vars = loop_index, matrix, idxs, weights

         def loop_condition(loop_idx, *_):
             return tf.greater(loop_idx, 0)

         def loop_body(loop_idx, mat, idxs, weights):
             x = mat[loop_idx]
             w = weights
             bias = tf.Variable(tf.constant(0.1, [2], dtype=tf.float64)) # Here?

             ...
             return loop_idx-1, mat, idxs, weights

         return tf.while_loop(loop_condition, loop_body, loop_vars, name=scope)[1]
Run Code Online (Sandbox Code Playgroud)

我正在用这种方式评估函数:

height = 2
width = 2
nodes = 4
matrix = np.ones((nodes, width+height))
weights = np.ones((width+height, width))/100
idxs = [0,0,1,2]
with …
Run Code Online (Sandbox Code Playgroud)

tensorflow

5
推荐指数
1
解决办法
4212
查看次数

标签 统计

class ×1

dynamic ×1

methods ×1

python ×1

tensorflow ×1