Python 返回*类名*
在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): """(
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声明要返回一个特定的命名类,所以要返回该类吗?