Python 替换实例方法

Python 替换实例方法,python,class,methods,attributes,instance,Python,Class,Methods,Attributes,Instance,我的理解正确吗 我试着以以下方式使用它: class A: def f(self): print('f') def g(self): print('g') def h(self): print('h') x = A() y = A() x.f = x.g # creates a new attribute 'f' for x x.f() # 'g'; resolves at the instance attribute level to call insta

我的理解正确吗

我试着以以下方式使用它:

class A:
  def f(self):
    print('f')
  def g(self):
    print('g')
  def h(self):
    print('h')

x = A()
y = A()
x.f = x.g # creates a new attribute 'f' for x
x.f() # 'g'; resolves at the instance attribute level to call instance method 'g'
y.f() # 'f'; instance methods are unaffected
A.f = A.h # redefines instance method 'f' to print 'h'
x.f() # 'g'; still resolves at the attribute level to call instance method 'g'
y.f() # 'h'; instance method 'f' now prints 'h'
A.g = A.h # redefines instance method 'g' to print 'h'
x.f() # 'g'; still calls the old instance method 'g' because it kept the link to it
y.f() # 'h'

这是否正确?这样可以吗?最初,我希望在每次调用
calculate\u attributes
时都能比检查
self.cache\u field
节省时间;但是我再也不确定它是否能节省时间了。

我认为这里的基本思想是正确的,只是做了一些小的修改。首先,

  class Attributes:
    def __init__(self, params, cache_field = None):
      # ...
      self.cache_field = cache_field
      if cache_field is None:
        # I hope I'm setting instance attribute only
        self.check_cache = self.check_external_cache
      else:
        self.check_cache = self.check_internal_cache
        self.internal_cache = {}

    def check_internal_cache(self, record):
      return self.internal_cache[record.id]

    def check_external_cache(self, record):
      return record[self.cache_field]

    def calculate_attributes(self, record):
      try:
        return self.check_cache(record) # I hope it will resolve to instance attribute
      except KeyError:
        # calculate and cache the value here
        # ...
应该读取类方法,而不是实例方法。你在这里换班。其次,这与此处定义的任何变量都不对应:

A.f = A.h # redefines instance method 'f' to print 'h'
我猜你的意思可能是
缓存\u字段

一般来说,在
\uuuu init\uuuu
中设置实例属性是完全正常和可接受的。这是一种方法而不是其他类型的对象并不重要——这与说
self.foo='bar'
没有任何区别


此外,有时这取决于,但一般来说,在
init
中设置方法确实比每次调用
check\u cache
时测试
cache\u字段要快。

。例如,使用实例方法作为处理程序的常规回调,但该回调可以根据状态进行更改。是的,它是
cache\u字段
,而不是
cache
。更新。。。是否有任何链接总结了更改方法的良好用例(在init内部或外部)?需要记住的一点是,这会创建一个会影响对象生命周期的引用周期。这里a.f或a.h都不是“类方法”,而是“未绑定的方法”,它们在Python@jsbueno,是的,我只是用速记。
    if cache is None: