简体   繁体   English

Python - __init__ 参数

[英]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. args,在第 10 号情况下应该返回一个 int,但返回的是一个元组。

It is because when you call the get_numero() method, self.__numero is returned.这是因为当您调用get_numero()方法时,会返回self.__numero And when looking at self.__numero in __init__() , it is returning args , which is always a Tuple, even if you have only 1 argument.当在__init__()中查看self.__numero时,它返回args ,它始终是一个元组,即使你只有 1 个参数。

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.通过 Python 规范args是一个元组,即使它包含单个元素。

Then, self.__numero stores a tuple.然后, self.__numero存储一个元组。 When you retrieve it and print it, it is still a tuple.当您检索它并打印它时,它仍然是一个元组。

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

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