Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回*类名*_Python - Fatal编程技术网

Python 返回*类名*

Python 返回*类名*,python,Python,在python中,方法返回类名意味着什么 我的意思是假设你有两个班: class TestClass: def __init__(self, board=[]): """(TestClass, int) -> NoneType """ self.board = [(0, [5,4,3,2,1]), (1, []), (2, []), (3, [])] def top_coin(self, idx): """(

在python中,方法返回类名意味着什么

我的意思是假设你有两个班:

class TestClass:
    def __init__(self, board=[]):
        """(TestClass, int) -> NoneType
        """
        self.board = [(0, [5,4,3,2,1]), (1, []), (2, []), (3, [])]

    def top_coin(self, idx):
        """(TestClass, int) -> Coin

        Return's a Coin.

        """
        if not self.board[idx][1]:
            return None
        return self.board[idx][1][-1]

class Coin:

    def __init__(self, length):
        """(Coin, int) -> NoneType

        >>> c = Coin(3)
        >>> c.length
        3

        """
        self.length = length

    def __repr__(self):
        """(Coin) -> str
        """
        return "Coin(" + str(self.length) + ")"    
您希望类TestClass中的top_coin方法返回一个coin。这是否意味着无论它返回什么,都应该用Coin类包裹起来?所以当你做

t1 = TestClass()
t1.top_coin(0)
Coin(1) ??

这意味着您必须返回类型为
Coin
的实例。例如:

class TestClass:
    ...
    def top_coin(self, size):
        ...
        return Coin(3) # you may change the parameter '3'
因此,当调用该方法时,可以将其存储为
Coin
类型的变量:

a_coin = t1.top_coin(0)

另外,在类
Coin
\uuuuu init\uuuu
方法中,您没有声明
长度。它将导致错误。

您的意思是因为docstring声明要返回一个特定的命名类,所以要返回该类吗?