python - 替换实例方法

标签 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 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'

我的理解正确吗?

我尝试通过以下方式使用它:

  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
        # ...

这能正常工作吗?这样做可以吗?最初,我希望与每次调用 calculate_attributes 时检查 self.cache_field 相比能够节省时间;但我不再确定它会节省任何时间。

最佳答案

我认为这里的基本想法是正确的,有一些小的修正。首先,

A.f = A.h # redefines instance method 'f' to print 'h'

应该读取方法,而不是实例方法。你要在这里改变类(class)。其次,这与此处定义的任何变量都不对应:

    if cache is None:

我猜你的意思是cache_field

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

此外,有时这取决于情况,但一般来说,在 init 中设置方法确实比每次 check_cache 测试 cache_field 更快> 被调用。

关于python - 替换实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9146784/

相关文章:

python - 让函数的唯一目的是调用另一个函数是个好主意吗?

java - 如何在Android Studio中使用View Parameter调用方法

c++ - 如何创建与系统函数同名的方法?

python - python中的matlab ismember函数

ios - 数组中的数组(二维数组?)

Python 脚本给出 `: No such file or directory`

php - $settings 数组或配置类来存储项目设置?

java - java中有些私有(private)内部类可以不继承吗?

Python哨兵控制循环

python - DateOffset Pandas 减法