Python实现指针式行为

2024-04-20 01:45:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须编写一个测试模块并且有c++背景。尽管如此,我知道python中没有指针,但如何实现以下目标:

我有一个测试方法,它看起来像这样的伪代码:

def check(self,obj,prop,value):
    if obj.prop <> value:  #this does not work, 
                           #getattr does not work either, (objects has no such method (interpreter output) 
                           #I am working with objects from InCyte's python interface
                           #the supplied findProp method does not do either (i get 
                           #None for objects I can access on the shell with obj.prop
                           #and yes I supply the method with a string 'prop'
        if self._autoadjust:
            print("Adjusting prop from x to y")
            obj.prop = value #setattr does not work, see above
        else:
            print("Warning Value != expected value for obj")

因为我想在不同的函数中检查许多不同的对象,所以我希望能够将check方法保持在适当的位置。在

一般来说,如何确保函数影响传递的对象而不创建副本?在

^{2}$

我不能使resize成为一个成员方法,因为myobj实现遥不可及,而且我不想在任何地方都输入myobj=resize(myobj, 10)

另外,我怎样才能使它能够访问函数中的那些属性,并将对象和属性名传递给它呢?在


Tags: the对象函数selfobjobjectsvaluecheck
3条回答

In general how do I ensure that a function affects the passed object and does not create a copy?

Python不是C++,除非显式复制否则不创建副本。在

I cant make resize a member method since myobj implementation is out of reach, and I don't want to type myobj=resize(myobj,10) everywere

我不明白?为什么应该是遥不可及的?如果有实例,则可以调用其方法。在

In general, how do I ensure that a function affects the passed object

通过在函数内部编写影响传入对象的代码,而不是将重新分配给名称。在

and does not create a copy?

除非你提出要求,否则永远不会创建副本。在

Python“变量”是事物的名称。它们不存储对象;它们引用对象。但是,与C++引用不同,它们可以被引用来引用其他的东西。在

当你写作的时候

def change(parameter):
    parameter = 42

x = 23
change(x)
# x is still 23

这本书还没有被复制,因为这个原因。原因是,在函数内部,parameter以传入的整数对象23的名称开头,然后parameter = 42行使parameter不再是{}的名称,而开始成为42的名称。在

如果你这么做的话

^{pr2}$

传入的参数会更改,因为列表上的.append会更改实际的列表对象。在

I can't make resize a member method since the myobj implementation is out of reach

这无关紧要。当Python编译时,没有类型检查步骤,也没有步骤来查找插入调用的方法的实现。所有这些都是在代码实际运行时处理的。代码将到达点myobj.resize(),查找myobj当前引用的任何对象的resize属性(毕竟,它甚至不能提前知道它处理的是什么类型的对象;变量在Python中没有类型,而对象有类型),并尝试调用它(如果(a)对象变了,则抛出适当的异常不具有该属性;(b)该属性实际上不是方法或其他类型的函数)。在

Also, how can I make it so that I can access those attributes in a function to which i pass the object and the attribute name? / getattr does not work either

当然,如果你使用得当的话。它不是内置在顶层的函数。与setattr相同。在

getattr不是一个方法,你需要像这样调用它

getattr(obj, prop)

类似地,setattr的名称如下

^{pr2}$

相关问题 更多 >