簡體   English   中英

python:強制只從另一個類方法中調用一個類方法?

[英]python: enforce that a class method is only called from within another class method?

我有一個帶有兩個方法A和B的類。該類將被子類化。 是否有一種優雅的方法強制B()僅從A()方法中的類對象上調用?

讓我們約束一下,說A()僅在一個地方被調用,但是子類實現A()並可以選擇在其中調用B()。 我想到的一種方法是,通過設置一個全局變量來包裝A()調用,該全局變量表示可以調用B(),而B()會在調用此變量時對其進行檢查。 這似乎並不優雅。

有什么建議么?

實際的私有方法是邪惡的。 通過添加前划線將您的方法標記為內部方法。 這告訴程序員不要使用它,除非他們知道自己在做什么。

盡管我不推薦這種做法,但這是可以使用sys._getframe()完成的一種方法:

import sys

class Base(object):
    def A(self):
        print '  in method A() of a {} instance'.format(self.__class__.__name__)

    def B(self):
        print '  in method B() of a {} instance'.format(self.__class__.__name__)
        if sys._getframe(1).f_code.co_name != 'A':
            print '    caller is not A(), aborting'
            return
        print '    called from A(), continuing execution...'

class Derived(Base):
    def A(self):
        print "  in method A() of a {} instance".format(self.__class__.__name__)
        print '    calling self.B() from A()'
        self.B()

print '== running tests =='
base = Base()
print 'calling base.A()'
base.A()
print 'calling base.B()'
base.B()
derived = Derived()
print 'calling derived.A()'
derived.A()
print 'calling derived.B()'
derived.B()

輸出:

== running tests ==
calling base.A()
  in method A() of a Base instance
calling base.B()
  in method B() of a Base instance
    caller is not A(), aborting
calling derived.A()
  in method A() of a Derived instance
    calling self.B() from A()
  in method B() of a Derived instance
    called from A(), continuing execution...
calling derived.B()
  in method B() of a Derived instance
    caller is not A(), aborting

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM