Disable class instance methods

How can I quickly disable all methods in an instance of a class based on a condition? My naive solution is to override with __getattr__, but this is not called when the function name already exists.

class my():
    def method1(self):
        print 'method1'
    def method2(self):
        print 'method2'
    def __getattr__(self, name):
        print 'Fetching '+str(name)
        if self.isValid():
            return getattr(self, name)
    def isValid(self):
        return False
if __name__ == '__main__':
    m=my()
    m.method1()
+3
source share
1 answer

, , __getattribute__, . , , : , , , self.isValid __getattribute__ , - (type(self).isValid(self) , , , ).

: ", , , classmethods. , , __getattribute__ (, - , ), , , ).

: State: . :.

class _NotValid(object):
  def isValid(self):
    return False
  def setValid(self, yesno):
    if yesno:
      self.__class__ = TheGoodOne

class TheGoodOne(object):
  def isValid(self):
    return True
  def setValid(self, yesno):
    if not yesno:
      self.__class__ = _NotValid
  # write all other methods here

setValid , __class__ , - , __class__ - , , , , , . , , " ", , .

__getattribute__ , (, , ;-), :

class _Valid(object):
  def __init__(self, actualobject):
    self._actualobject = actualobject
  # all actual methods go here
  # keeping state in self._actualobject

class Wrapit(object):
  def __init__(self):
    self._themethods = _Valid(self)
  def isValid(self):
    # whatever logic you want
    # (DON'T call other self. methods!-)
    return False
  def __getattr__(self, n):
    if self.isValid():
      return getattr(self._themethods, n)
    raise AttributeError(n)

, __getattribute__, , __getattr__ , - () __dict__, ; . _Valid self._actualobject, - ( , , Q, , , ). , __getattribute__, ( ).

, , . , weakref Python, - , , , . (, _actualobject _Valid , _themethods).

+5

Source: https://habr.com/ru/post/1733367/


All Articles