简体   繁体   English

如何从Python函数返回多个变量

[英]How to return multiple variables from a Python function

I am new to Python and trying to experiment by creating an address book. 我是Python的新手,正在尝试通过创建通讯录进行试验。 I suspect I have a problem with the displayPerson function. 我怀疑我的displayPerson函数有问题。 Can I not return multiple variables at the same time? 我不能同时返回多个变量吗?

def lowercasewrapper(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).lower()
    return wrapper

#Class with object attributes
class People():
    numofpeeps = 0
    listofpeeps = []
    def __init__(self, name, age, phone, fblink):
        self.name=name
        self.age=age
        self.phone=phone
        self.fblink=fblink
        People.numofpeeps += 1
        People.listofpeeps.append(self.age)

    @lowercasewrapper #calling the wrapper, to make all strings lowercase
    def displayPerson(self): 
        return self.name, self.age, self.phone, self.fblink

george=People("gEORge", "5", "503-405-4021", "http://facebook.com/boobs")
dave=People("dave", "10", "971-863-3905", "http://boobs.com")
charlie=People("CHARLIE", "19", "823-405-2942", "http://boobs.com")

print george.displayPerson()
print "Total number of people: ", People.numofpeeps
print "List of ages: ", People.listofpeeps


error shows the following: File "example.py", line 54, in <module>
    print george.displayPerson()
  File "example.py", line 31, in wrapper
    return func(*args, **kwargs).lower()
AttributeError: 'tuple' object has no attribute 'lower'

Just 只是

def myFunc():
    return 1, 2

and in caller 和来电者

var1, var2 = yourFunc()

Exception is raised by the lowercasewrapper not the displayPerson . lowercasewrapperdisplayPerson而不是displayPerson引发异常。 You can use this instead: 您可以改用以下方法:

def lowercasewrapper(func):
    def wrapper(*args, **kwargs):
        return [x.lower() for x in func(*args, **kwargs)]
    return wrapper

Read @DonaldMiner answer for a better explanation. 阅读@DonaldMiner答案以获得更好的解释。

In this line: 在这一行:

    return func(*args, **kwargs).lower()

You are taking the return of that and calling it lower. 您正在获得回报,并将其降低。 When you do: 当您这样做时:

    return self.name, self.age, self.phone, self.fblink

What that really does is packs those 4 variables into a tuple, and then returns that. 真正的作用是将这四个变量打包到一个元组中,然后将其返回。

So, unfortunately you are trying to call .lower() on a tuple, not on each item. 因此,不幸的是,您尝试在元组而不是每个项目上调用.lower() Instead, you want to go through and call .lower() on everything inside: 相反,您想要遍历并调用.lower()里面的所有内容:

def lowercasewrapper(func):
    def wrapper(*args, **kwargs):

        return tuple(item.lower() for item in func(*args, **kwargs))
    return wrapper

This uses a list comrpehension. 这使用列表理解。 If you haven't seen that syntax yet, you might want to use a for-loop to iterate over each item and lower case it. 如果尚未看到该语法,则可能要使用for循环遍历每个项目并将其小写。

Sure, you can return multiple values from a function. 当然,您可以从一个函数返回多个值。 That's not your problem. 那不是你的问题。

When you return multiple values from a function, Python automatically wraps them up in a tuple. 当您从函数返回多个值时,Python会自动将它们包装在一个元组中。 So when you call displayPerson , it returns a tuple containing the person's name, age, phone number and facebook link in that order. 因此,当您调用displayPerson ,它将返回一个包含该人的姓名,年龄,电话号码和Facebook链接的元组。

Now, in your lowercase wrapper you take the result from calling displayPerson , and call the lower method on it. 现在,在小写包装器中,您从调用displayPerson获得结果,并在其上调用lower方法。 Unfortunately, tuples don't have a lower method. 不幸的是,元组没有lower方法。

Instead, you'll need to return a new tuple with each of the elements individually converted to lower case: 相反,您需要返回一个新的元组,并将每个元素分别转换为小写字母:

def lowercasewrapper(func):
    def wrapper(*args, **kwargs):
        # Get initial result of your function.
        initial_tuple = func(*args, **kwargs)
        # Create a new tuple consisting of each member of the
        # initial tuple, converted to lower case.
        new_tuple = tuple([x.lower() for x in initial_tuple])
        return new_tuple
    return wrapper

Note: this could be done in a single line, I used a couple here to illustrate what's going on. 注意:这可以在一行中完成,我在这里使用了两个示例来说明发生了什么。

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

相关问题 如何从python中的函数返回字典和多个变量? - How to return a dictionary and multiple variables from a function in python? 你如何从python中的函数返回多个变量 - How do you return multiple variables from a function in python 如何从python返回多个变量到bash - How to return multiple variables from python to bash 如何返回在python函数中定义和启动的多个变量? - How can you return multiple variables defined and initiated in a function in python? 我如何从 Python 函数返回多个变量 - How do i return multiples variables from Python function 如何将变量从 PyQt5 UI 返回到 Main 函数 - Python - How to return variables from PyQt5 UI to Main function - Python python中的函数多次返回 - multiple return from function in python 如何将来自 function 的多个结果存储在 for 循环中作为 Python 中的唯一变量? - How to store multiple results from a function in a for loop as unique variables in Python? 如何访问在python中编译的多个返回变量 - How to access the multiple return variables compiled in python Python语法:从三元表达式中的函数返回值解压缩多个变量会产生意外结果 - Python syntax: unpacking multiple variables from function return value in ternary expression gives unexpected result
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM