python:强制只从另一个类方法中调用类方法?

时间:2011-01-26 10:49:47

标签: python

我有一个包含两个方法A和B的类。该类将被子类化。是否有一种优雅的方法来强制B()只在A()方法中调用类的对象?

让我们约束它并说A()只在一个地方调用,但是子类实现A()并且可以选择在其中调用B()。我想到这样做的一种方法是用一个全局变量来包装A()调用,该变量表示可以调用B(),而B()会在调用它时检查这个变量。这看起来并不优雅。

有什么建议吗?

2 个答案:

答案 0 :(得分:5)

实际的私人方法是邪恶的。通过添加前导下划线将您的方法标记为内部。这告诉程序员不要使用它,除非他们知道他们在做什么。

答案 1 :(得分:2)

虽然我不推荐这种做法,但可以使用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