[英]Access method from another class in python
我有以下代碼:
from DoublyLinkedList import DoublyLinkedList
class LinkedQueue():
def __init__(self):
self.data = DoublyLinkedList()
def enqueue(self, val):
self.data.add_first(val)
x = LinkedQueue()
x.enqueue(2)
x.enqueue(4)
print(x)
其中 LinkedQueue 使用 DoublyLinkedList 作為數據成員。 我使用 2 和 4 作為值加載列表,並嘗試使用 DoublyLinkedList class repr方法打印 DLL "x"。 這將返回<__main__.LinkedQueue object at 0x00BBEC90>
而不是所需的[2,4]
。
下面的 DoubleLinkedList repr方法:
class DoublyLinkedList:
def __repr__(self):
return "[" + ','.join[str(i) for i in self] + "]"
DLL 是x.data
,而不是x
。 如果要調用 DLL 方法,則需要打印:
print(x.data)
如果要打印LinkedQueue
以自動執行此操作,則需要在 class 中定義一個方法:
class LinkedQueue():
...
def __repr__(self):
return repr(self.data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.