在Python中对用户定义的对象使用按引用调用的Out参数

2024-04-19 12:41:03 发布

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

我有一个用户定义的对象。我想作为引用(out参数)传递,以便在函数内部更改输入对象的值并返回到被调用的函数。这可以通过使用列表或字典(即可变对象)来实现。但是如何在不使用列表和字典的情况下实现自定义对象。 检查下面的代码段示例:-你知道吗

class Test:          
    def __init__(self,data):
        self.data = data

def display(root):    # Simple Display function
    print(root.data)

#Don't want to use List to do pass by reference and out parameter. Instead pass object itself.
def assign(root,args): 
    if root is not None:
        args[0] = root

#Passed object itself, not as List     
def assign1(root,temp):
    if root is not None:
        temp = root

#Driver Function call    
root = Test(10)
display(root)
temp = None
args = [temp]
assign(root,args)   # Function in which args passed as out parameter
display(args[0])    # Gives Output: 10 

temp1 = None 
assign1(root,temp1) # Function in which object passed as out parameter
print(temp1)        # Gives Output: None
display(temp1)      # AttributeError: 'NoneType' object has no attribute 'data'

也许我错过了什么。你知道吗


Tags: 对象nonedataobjectparameterdefasdisplay