2017-03-02 4 views
0

子クラスを使用するときに、ユーザーが親クラスのメソッドを呼び出すのを防ぐことができるかどうかは疑問です。同時に、私はこれらのメソッドが子クラス自身のメソッドに利用可能であることを望みます。子クラスのユーザーからスーパークラスメソッドを隠す

たとえば、リンクリストの実装があるとします。私は継承してスタックADTの実装をベースにしています(良い設計であるかどうかはわかりません...)。したがって、LinkedListクラスのメソッドをStackクラスのユーザーから「隠す」ことを望みます。

の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) 
+1

いいえ、それはおそらく良いデザインではありません。同じインタフェースを公開したくない場合は、* compose *は継承しません。 – jonrsharpe

+0

StackがLinkedListが作るインターフェイスの約束を果たそうとしない場合、LinkedListを拡張すべきではありません。 – user2357112

+0

公式のPythonのドキュメント** ["9.6。プライベート変数"](https://docs.python.org/3/tutorial/classes.html?highlight = private#private-variables)**では、 'class'の中のメソッドを保護することができます。 2回のアンダースコア(例: '__private_search(self):')で始まる名前を付けるだけで、その関数を宣言してください。 –

答えて

-1

ここでは、クラスで保護され、プライベートメソッドを宣言するための正式な構文です。

  1. 親クラスで宣言された保護されたメソッドは、子クラスから呼び出すことができます。
  2. 親クラスで宣言されたプライベートメソッドは、子クラスから非表示になります。

上げ例外は次のとおりです。

# AttributeError: '<ChildClass>' object has no attribute '__<private_function>'

ステップ1からclass Parentの両方の民間および保護されたメソッドを宣言します。

class Parent(object): 
    # a private method starts by 2 '_' 
    def __parent_private(self): 
     print('inside __parent_private()') 

    # a protected method starts by 1 '_' 
    def _parent_protected(self): 
     print('inside _parent_protected()') 

ステップ2からclass Childから両関数を呼び出す関数を宣言する。

class Child(Parent): 

    def call__parent_private(self): 
     self.__parent_private() 

    def call_parent_protected(self): 
     self._parent_protected() 

ステップ3 - プライベートおよび保護されたアクセスをチェックするためにclass Childのインスタンスを作成します。

myChild = Child() 

Check of protected method from the Child class ==> Access is allowed

# internal access of protected method 
myChild.call_parent_protected() 

出力: "inside _parent_protected()"

# direct access of protected method 
myChild._parent_protected() 

出力: "inside _parent_protected()"

Check of private method from the Child class ==> Access is denied

# internal access of private method 
myChild.call__parent_private() 

エラー: "AttributeError: 'Child' object has no attribute '_Child__parent_private'"

# direct access of private method 
myChild.__parent_private() 

は、エラー: "AttributeError: 'Child' object has no attribute '__parent_private'"

関連する問題