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'
Is my understanding correct?
I’m trying to use this in the following way:
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
# ...
Would this work correctly? Is it ok to do this? Originally I was hoping to save time compared to checking self.cache_field in every call to calculate_attributes; but I’m no longer sure it would save any time.
I think the basic idea here is correct, with a couple of minor corrections. First,
That should read class method, not instance method. You’re changing the class here. And second, this doesn’t correspond to any defined variable here:
I guess maybe you mean
cache_field?In general, setting instance attributes in
__init__is perfectly normal and acceptable. It doesn’t matter that this is a method rather than some other kind of object — it’s not any different from sayingself.foo = 'bar'.Also, sometimes this depends, but in general, it is indeed faster to set the method in
initthan to testcache_fieldevery timecheck_cacheis called.