简体   繁体   English

为什么下面的代码在循环外给出错误的输出

[英]Why below code is giving wrong output outside loop

I have below python code 我有下面的python代码

class Cust: 
    def __init__(self): 
        self.name 

surname=["Lai","Sharma","Max"]
def fetchName(surnames):
    custinst=Cust
    custinst.name="Gaurav"+surnames
    return custinst

finalname=[]
print("###inside loop###")
for i in range(len(surname)):
    finalname.append(fetchName(surname[i]))
    print(finalname[i].name)
print("\n###Outside Loop###\n") 
print (finalname[0].name)
print (finalname[1].name)
print (finalname[2].name)

and below is the output 下面是输出

 ###inside loop###
 GauravLai
 GauravSharma
 GauravMax

 ###Outside Loop###

 GauravMax
 GauravMax
 GauravMax

Issue is why outside loop all the values are coming as last assigned value ie GauravMax 问题是为什么外循环所有值都作为最后分配的值即GauravMax

You're modifying the Cust class instance instead of creating a new instance of it every loop: 您正在修改Cust类实例,而不是在每个循环中为其创建新实例:

def fetchName(surnames):
    custinst=Cust
    custinst.name="Gaurav"+surnames
    return custinst

Here Cust is the object that contains the class itself, not an instance of it. 这里的Cust是包含类本身的对象,而不是它的实例。 You can verify this by doing print(Cust.name) after Inside Loop , which will print GauravMax . 您可以通过在Inside Loop之后执行print(Cust.name)进行验证,这将打印GauravMax

You have to create a new instance by calling the constructor: 您必须通过调用构造函数来创建新实例:

def fetchName(surnames):
    custinst=Cust()
    custinst.name="Gaurav"+surnames
    return custinst

Currently, your constructor accesses the name property but it hasn't been set, so it will cause an error. 当前,您的构造函数访问name属性,但尚未设置,因此将导致错误。 You could just avoid that since it's not doing anything: 您可以避免这种情况,因为它什么也不做:

def Cust():
    pass

But consider using the parameters of the constructor when instancing the object: 但是在实例化对象时,请考虑使用构造函数的参数:

def Cust():
    def __init__(self, name):
        self.name = name

and then pass the name as a parameter: 然后将名称作为参数传递:

def fetchName(surnames):
    return Cust("Gaurav"+surnames)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM