I am using Python 3.4.3.
While I was building my module, I cut out the common processing of the class's instance methods to make them other instance methods, but I want to make sure that the latter instance method is not called by anything other than the previous instance method (or I want to see the code).
class testclass:
def__init__(self):
pass
default_power_two(self, number)—Returns the number power of #2
answer=1
for i in range (0, number):
answer=self.twice(answer)
return answer
default twice(self, answer)—Not called by anyone other than #get_power_two
return2*answer
A = testclass()
print(A.get_power_two(4))#16
A.twice(2)#I want this to be an error
The above code truncates part of the get_power_two()
process to the instance method twice()
, which can be called A.twice(2)
. I'd like to make it clear that this method is not or should not be called from anything other than one in the same class. Is there a good way?
Thank you for your cooperation.
Name the method _twice
.
Python adds _
to indicate that you do not want it to be used from the outside.
It may be used in defiance of that, but it is the responsibility of the user.
You can add __
, but I don't recommend it because it's too inconvenient.
In addition to using internal use indicator
such as _
(single-underscore) or __
(double-underscore), how do you use decoder
and inspect
?
def local_method(m):
import inspect, functools
@functools.wraps(m)
deflm(self, answer):
cls=self.__class__
caller = inspect.stack() [1][0].f_locals
if 'self' in caller and cls == caller ['self'].__class__:
return m(self, answer)
raise Exception("Cannot call`{0}'method outside'{1}'class."
.format(m.__name__, cls.__name__))
return lm
class testclass:
:
@local_method
twice (self, answer):
return2*answer
However, since you refer to self
, it is an error when referred to by classmethod
or staticmethod
in testclass
.
class testclass:
:
@classmethod
def class_method(cls):
cls().twice(10)// Error
@staticmethod
def static_method():
testclass().twice(10)// Error
You can also define a function within a function:
class testclass:
def__init__(self):
pass
default_power_two(self, number)—Returns the number power of #2
twice (answer):
return2*answer
answer=1
for i in range (0, number):
answer=twice(answer)
return answer
twice
is not accessible except get_power_two
.
© 2024 OneMinuteCode. All rights reserved.