gpt4 book ai didi

python - 替换实例方法

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:38 25 4
gpt4 key购买 nike

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'

应该读作 方法,而不是实例方法。你在这里改变类。其次,这不对应于此处定义的任何变量:

    if cache is None:

我猜你是说cache_field

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com