我想知道是否有可能阻止用戶在使用子類時調用父類的方法。同時,我希望這些方法可以用於孩子班級的方法。從子類的用戶隱藏超類方法
例如,假設我有一個鏈接列表的實現。然後,我通過繼承(不知道它是否是好的設計...)來爲它構建一個ADT堆棧實現。因此,我希望從Stack類的用戶中「隱藏」LinkedList類的方法。
的LinkedList:
class LinkedList(object):
class Node(object):
"""
Inner class of LinkedList. Contains a blueprint for a node of the LinkedList
"""
def __init__(self, v, n=None):
"""
Initializes a List node with payload v and link n
"""
self.value=v
self.next=n
def __init__(self):
"""
Initializes a LinkedList and sets list head to None
"""
self.head=None
def insert(self, v):
"""
Adds an item with payload v to beginning of the list
in O(1) time
"""
Node = self.Node(v, self.head)
self.head = Node
print("Added item: ", Node.value, "self.head: ", self.head.value)
def size(self):
"""
Returns the current size of the list. O(n), linear time
"""
current = self.head
count = 0
while current:
count += 1
current = current.next
return count
def search(self, v):
"""
Searches the list for a node with payload v. Returns the node object or None if not found. Time complexity is O(n) in worst case.
"""
current = self.head
found = False
while current and not found:
if current.value == v:
found = True
else:
current = current.next
if not current:
return None
return current
def delete(self, v):
"""
Searches the list for a node with payload v. Returns the node object or None if not found. Time complexity is O(n) in worst case.
"""
current = self.head
previous = None
found = False
while current and not found:
if current.value == v:
found = True
else:
previous = current
current = current.next
# nothing found, return None
if not current:
return None
# the case where first item is being deleted
if not previous:
self.head = current.next
# item from inside of the list is being deleted
else:
previous.next = current.next
return current
def __str__(self):
"""
Prints the current list in the form of a Python list
"""
current = self.head
toPrint = []
while current != None:
toPrint.append(current.value)
current = current.next
return str(toPrint)
堆棧:
from PythonADT.lists import LinkedList
class Stack(LinkedList):
def __init__(self):
LinkedList.__init__(self)
不,這可能不是一個好的設計。如果你不想公開相同的接口,*撰寫*不*繼承*。 – jonrsharpe
如果Stack不會履行LinkedList所做的接口承諾,它不應該擴展LinkedList。 – user2357112
正如Python官方文檔** [「9.6。Private Variables」](https://docs.python.org/3/tutorial/classes.html?highlight = private#private-variables)**,可以保護'class'中的方法。只需通過兩次下劃線(例如'__private_search(self):')來聲明該函數即可。 –