# 使用類/靜態方法作為同一類方法中的默認參數值

class SillyWalk(object):
@staticmethod
def is_silly_enough(walk):
return (False, "It's never silly enough")
def walk(self, appraisal_method=is_silly_enough):
self.do_stuff()
(was_good_enough, reason) = appraisal_method(self)
if not was_good_enough:
self.execute_self_modifying_code(reason)
return appraisal_method
def do_stuff(self):
pass
def execute_self_modifying_code(self, problem):
from __future__ import deepjuju
deepjuju.kiss_booboo_better(self, problem)


>>> silly_walk = SillyWalk()
>>> appraise = walk()
>>> is_good_walk = appraise(silly_walk)


• call appraisal_method.__get__(instance, owner)(...) instead of just calling appraisal_method(...)
• or assign it as the attribute of some object, then reference that object property as a method that we call as we would call appraisal_method.

Given that neither of these solutions seem particularly Pythonic™, I'm wondering if there is perhaps a better way to get this sort of functionality. I essentially want a way to specify that a method should, by default, use a particular class or static method defined within the scope of the same class to carry out some portion of its daily routine.

## 最佳答案

def walk(self, appraisal_method=unstaticmethod(is_silly_enough)):


def unstaticmethod(static):
"""Retrieve the original function from a staticmethod object.

This is intended for use in binding class method default values
to static methods of the same class.

For example:
>>> class C(object):
...     @staticmethod
...     def s(*args, **kwargs):
...         return (args, kwargs)
...     def m(self, args=[], kwargs={}, f=unstaticmethod(s)):
...         return f(*args, **kwargs)
>>> o = C()
>>> o.s(1, 2, 3)
((1, 2, 3), {})
>>> o.m((1, 2, 3))
((1, 2, 3), {})
"""
# TODO: Technically we should be passing the actual class of the owner
#         instead of object, but
#         I don't know if there's a way to get that info dynamically,
#         since the class is not actually declared
#         when this function is called during class method definition.
#       I need to figure out if passing object instead
#         is going to be an issue.
return static.__get__(None, object)