クラスの場合parent
、クラスの他のメソッドと同じように、self パラメータを指定してそれを使用することで、その属性にアクセスできます。
それがクラスでない場合、おそらくこれを処理する最善の方法は、メソッドとして直接ではなく、ラッパー/ファクトリ/何か内に関数を記述することです。
def some_method_wrapper(parent):
def some_method():
#access any parent attribute
#by using the parent positional argument passed to the function
print parent.desired_attribute
return 'blabla'
setattr(parent, 'new_attr', some_method)
その後、使用parent.new_attr()
して、必要な親属性を印刷/操作/何でもできるようになります。
これを使用して関数のカウンターを操作する方法 (または、関数キャッシュをフラッシュする方法) の具体的な例を次に示します。
def parent_function(numbers):
# do something with numbers
parent_function.counter += 1
return sum(numbers)
parent_function.counter = 0
def add_reset_function(parent):
def reset_counter():
parent.counter = 0
setattr(parent, 'reset', reset_counter)
# call parent_function a few times
numbers = [1, 2, 3]
for i in range(4): parent_function(numbers)
print parent_function.counter # 4
add_reset_function(parent_function)
# call the reset function just added
parent_function.reset()
print parent_function.counter # 0
parent_function(numbers)
print parent_function.counter # 1