简体   繁体   中英

Python - __init__ args

I have the following problem.

class Operacoes(object):

    def __init__(self, *args):
        self.__numero = args

    def get_numero(self) -> int:
        return self.__numero

x = Operacoes(10).get_numero()
print(x)
#(10,)

This is making me very intrigued, why does anyone know how to tell me?

args, should return an int in case number 10, but a Tuple is returning.

It is because when you call the get_numero() method, self.__numero is returned. And when looking at self.__numero in __init__() , it is returning args , which is always a Tuple, even if you have only 1 argument.

Let's look closer at the syntax. You assigned

*args = 10

The star is really important here because it does unpacking of a tuple/list. By Python specification args is a tuple, even if it contains a single element.

Then, self.__numero stores a tuple. When you retrieve it and print it, it is still a tuple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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