python:如何确保类方法仅在另一个类方法内被调用?
我有一个类,这个类里面有两个方法,分别叫做A和B。这个类会被其他类继承。有没有什么好的办法可以确保B()这个方法只能在A()方法里面被调用呢?
为了简化问题,我们假设A()方法只在一个地方被调用,但子类可以实现A()方法,并且可以选择在里面调用B()。我想到的一种方法是,在调用A()的时候设置一个全局变量,表示可以调用B(),然后B()在被调用时检查这个变量。不过这样做看起来不是很优雅。
有没有什么好的建议呢?
2 个回答
5
真正的私有方法其实是不太好的做法。你可以通过在方法前面加一个下划线来标记它为内部方法。这是告诉其他程序员,除非他们知道自己在做什么,否则不要使用这个方法。
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