【问题标题】:Overwrite several methods of a class with a loop用循环覆盖一个类的几个方法
【发布时间】:2016-05-30 10:13:36
【问题描述】:

我想知道是否有一种简单的方法可以对一个类的多个方法进行一些相同的编辑。一个例子:

class Dog():
    def __init__(self):
        self.name = 'abc'
        self.age = 1

    def setName(self, newValue):
        self.name = newValue

    def setAge(self, newValue):
        self.age = newValue

class TalkingDog(Dog):

    def __init__(self):
        super().__init__()
        # The end is in pseudo code : 
        for method in TalkingDog.allMethods :
            method = method + 'print('I have been edited !')'

我知道我也可以覆盖每个方法,但是在有几十个方法的情况下,这会有点无聊......

所以我尝试了这个:

class TalkingDog(Dog):

    def __init__(self):
        super().__init__()
        for method in self.__dir__():
            if method.startswith('set'):
                oldMethod = getattr(self, method)
                def _newMethod(newValue):
                    oldMethod(newValue)
                    print('I have been edited !')
                setattr(self, method, _newMethod)


a = TalkingDog()
print(a.setName) >>> <function TalkingDog.__init__.<locals>._newMethod at 0x0000000002C350D0>

这几乎可行,但 setName 不再是一种方法。它是一个包含函数的属性。我完全理解为什么,但我正在努力获得更清晰的结果。这样一来,我以后就有可能遇到问题。例如,我不能将库pickle 与该对象一起使用(收到错误_pickle.PicklingError: Can't pickle &lt;function TalkingDog.__init__.&lt;locals&gt;._newMethod at 0x00000000003DCBF8&gt;: attribute lookup _newMethod on __main__ failed)。

【问题讨论】:

  • 使用属性,而不是set 和get 方法:stackoverflow.com/q/1554546/3001761
  • 另外,这个的实际用例是什么?你真的在做会说话的狗吗?如果是这样,狗不应该在他的年龄改变时说话。如果你想让狗说话,让他和改变年龄分开说话。
  • @jonrsharpe 我不明白为什么以及如何在这种情况下使用属性对我有帮助。
  • @Morgan 他们没有解决你的问题(这就是为什么它是评论而不是答案),这只是一个普遍的改进。你应该总是使用属性并且从不在Python中get和set。
  • @Morgan 请注意,您的minimal reproducible example 应该实际说明您的问题。否则很难就应该采用何种方法提出有用的建议。

标签: python class methods


【解决方案1】:

执行此操作的 Pythonic 方式可能是使用 descriptor protocol,这也是属性使用的方式:

class VocalAttribute:

    def __init__(self, name, feedback):
        """Called when you first create the descriptor."""
        self.name = name  # the name of the attribute 'behind' the property
        self.feedback = feedback  # the feedback to show when the value changes

    def __get__(self, obj):
        """Called when you get the descriptor value."""
        return getattr(obj, self.name)

    def __set__(self, obj, value):
        """Called when you set the descriptor value."""
        prev = getattr(obj, self.name, None)
        if value != prev:
            setattr(obj, self.name, value)
            print(self.feedback)

    def __delete__(self, obj):
        """Called when you delete the descriptor value."""
        delattr(obj, self.name)


class Foo:

    bar = VocalAttribute('_bar', 'I have been edited!')


foo = Foo()

print('1.')

foo.bar = 'hello'

print('2.')

foo.bar = 'hello'

print('3.')

foo.bar = 'world'

输出:

1.
I have been edited!
2.
3.
I have been edited!

请注意,这只在新值与旧值不同时提供反馈 - 您可以在 __set__ 中根据需要调整行为。这也意味着您可以直接读取并分配给foo.bar,而不需要调用 getter 和 setter(这是什么,Java?)

【讨论】:

  • 我不熟悉描述符协议。我将阅读更多关于它的内容并在我的代码上进行尝试。谢谢您的帮助 ! :)
【解决方案2】:

因为装饰器可以在这里显式调用一种使用它的方法:

def updater(obj, call_back, call_back_args=(), call_back_kw=None, replace=False):
    # ability to be called on the fly with different args and kw for the callback
    # now it returns the updated obj (instance or class) 
    # but could a be factory returning a new obj in this case make a copy of obj, update this coy and return it

    def update_function(fn, *args, **kw):
        def wrapper(*args, **kw):
            if replace:
                # call only the callback
                res = call_back(*call_back_args, **call_back_kw)
            else:
                res = fn(*args, **kw)
                call_back(*call_back_args, **call_back_kw)
            return res
        return wrapper

    # get all methods of the obj
    # and apply update_function (a decorator) to all methods
    for name, m in inspect.getmembers(
            obj, predicate=lambda x: inspect.isfunction(x) or inspect.ismethod(x)):
        # make the selection here
        # could be made on the name for instance
        if not name.startswith('_'):
            new_m = update_function(m)
            setattr(obj, name, new_m)

    return obj

# declare a callback 
def call_back(*args, **kw):
    # simple callback
    print("I have been edited and called with %r args and %r kw " % (args, kw))

a = Dog()

# could be called on instance or class
# apply the callback on all "public" methods 
updater(
    a,
    call_back,
    call_back_args=(2, 3, 4),
    call_back_kw={"kw1": "v_1"}
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    相关资源
    最近更新 更多