如何在python中的派生类中调用某个方法时调用基类函数?

时间:2014-08-07 18:33:15

标签: python inheritance

我在python中定义基类,如

class Base(object): 
    def __init__(self):
        self._changed = False

和一些派生类:

class Car(Base):
    def set_type(self, type_):
        # do something

    def set_mileage(self, mileage):
        # do something

class Flower(base):
    def set_name(self, name):
        # do something

在这个例子中,我现在想要设置属性' _changed'每当我调用其中一个派生类的True方法时,到set。我只想添加一行

self._changed = True

到每个set方法,或使用装饰器,但每当调用名称以' set _'开头的方法时,我正在寻找一种更方便和自动的方法。我正在考虑使用__getattribute__,如下所示未尝试过(而不是工作示例:

def __getattribute__(self, name):
    if name.startswith('set_'):
        self._changed = True
    return self.__getattribute__(name)

那么如何以正确的方式实现呢?

3 个答案:

答案 0 :(得分:2)

更新:这次使用包含setter和getter的元类和描述符的完整工作示例:

class Field(object):

    def __get__(self, ins, type):
        return getattr(ins, self.field_name, None)

    def __set__(self, ins, val):
        setattr(ins, self.field_name, val)
        ins._changed = True

class Meta(type):
    def __new__(cls, clsname, bases, dct):
        for k, v in dct.items():
            if isinstance(v, Field):
                v.field_name = '_' + k
        return type.__new__(cls, clsname, bases, dct)

class Base(object):
    __metaclass__ = Meta
    def __init__(self):
        self._changed = False

class Car(Base):

    type = Field()
    mileage = Field()

class Flower(Base):

    name = Field()

<强>演示:

>>> c = Car()
>>> c._changed
False
>>> c.type = "4X4"
>>> c._changed
True
>>> c1 = Car()
>>> c1._changed
False
>>> c1.mileage = 100
>>> c1._changed
True
>>> c.type
'4X4'
>>> c1.mileage
100
>>> f = Flower()
>>> f._changed
False
>>> f.name = "Rose"
>>> f._changed
True
>>> f.name
'Rose'

答案 1 :(得分:0)

我会使用装饰器。这样的事情(未经测试):

def isGet(func):
    def newFunc(self, var):
        self._changed = True
        func(self, var)
        return
    return newFunc

然后在任何 get 方法中,您想要这种行为,只需执行

即可
@isGet
def set_mileage(self, mileage):
    # dosomething

答案 2 :(得分:0)

元类可以在这里工作:

from types import FunctionType
from functools import wraps

class Setter(type):
    def __new__(cls, clsname, bases, dct):
        for item in dct:
            if item.startswith("set_") and isinstance(dct[item], FunctionType):
                dct[item] = cls.changer(dct[item])
        return super(Setter, cls).__new__(cls, clsname, bases, dct)

    @staticmethod
    def changer(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            self._changed = True
            return func(self, *args, **kwargs)
        return wrapper


class Base(object): 
    __metaclass__ = Setter
    def __init__(self):
        self._changed = False

然后就像你通常那样从Base继承。

样本用法:

>>> from meta import Car
>>> c = Car()
>>> c._changed
False
>>> c.set_type("blah")
ok
>>> c._changed
True

元类只是自动装饰你班级中的任何方法&#39;以__dict__开头的set_