打印功能属性

时间:2014-08-27 20:30:58

标签: python string function attributes concatenation

在一个模块中,我试图收集raw_inputs并用空格连接每个。 然后,我想打印出一个raw_input的结果:

def human_infoz():

    name = raw_input("Enter human name> ")
    address = raw_input("Human Address> ")
    phone = raw_input("Human Phone Number> ")
    email = raw_input("Human Email> ")
    listinfo = ["", name, address, phone, email, ""]
    return ' '.join(listinfo)

go = human_infoz()
print go.name

raw_input工作得很好,但是当脚本到达namez时,它会放弃。

AttributeError: 'str' object has no attribute 'name'

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您可以在代码中添加print name,在class name之内创建attribute,或者只返回第二个arg的分配名称为def human_infoz(): name = raw_input("Enter human name> ") address = raw_input("Human Address> ") phone = raw_input("Human Phone Number> ") email = raw_input("Human Email> ") listinfo = ["", name, address, phone, email, ""] return ' '.join(listinfo),name go = human_infoz() namez = go[1] print namez 下面:

def human_infoz():

    name = raw_input("Enter human name> ")
    address = raw_input("Human Address> ")
    phone = raw_input("Human Phone Number> ")
    email = raw_input("Human Email> ")
    listinfo = [name, address, phone, email]
    return listinfo

go = human_infoz()
namez,add,phone,email = go 

如果您希望所有细节都返回列表:

print namez,add,phone,email

打印所有细节:

class

要像在尝试提问一样进行访问,您需要class Details(): def __init__(self): self.name = raw_input("Enter human name> ") self.address = raw_input("Human Address> ") self.phone = raw_input("Human Phone Number> ") self.email = raw_input("Human Email> ") self.info = [self.name, self.address, self.phone, self.email] go = Details() # create instance # print details by accessing the instance attributes print go.name,go.address,go.email,go.phone,go.info

这是一个非常基本的例子:

{{1}}

答案 1 :(得分:0)

如果要按名称访问这些变量,为什么不使用字典?

def human_infoz():

    name = raw_input("Enter human name> ")
    address = raw_input("Human Address> ")
    phone = raw_input("Human Phone Number> ")
    email = raw_input("Human Email> ")
    listinfo = {
        "name": name,
        "address": address,
        "phone": phone,
        "email": email
    }
    return listinfo

go = human_infoz()
print go["name"]