编程语言
首页 > 编程语言> > 没有属性样板的Python类

没有属性样板的Python类

作者:互联网

我的许多课程都类似于以下课程来代表帐户

class Account(object):
    def __init__(self, first, last, age, id, balance):
        self.first = first
        self.last = last
        self.age = age
        self.id = id
        self.balance = balance

    def _info(self):
        return self.first, self.last, self.age, self.id, self.balance

    def __eq__(self, other):
        return self._info == other._info()

    def __hash__(self):
        return hash((type(self), self.info()))

    def ... # other methods follow

但实际上,唯一相关的信息是我关心的属性列表,包括首尾,年龄,ID,余额.是否有标准方法定义遵循此结构的Python类?

乍一看,我想到过namedtuple,但是我不确定那是否允许我在事实之后添加其他方法.真的,我想要类似以下的东西

class Account(object):
    attributes = "first last age id balance"

    def ... # other methods

最好的方法是什么?

解决方法:

不知道这是多么惯用,但是以下内容可以满足您的要求:

class Slottable:
    def __init__(self, *args):
        for slot, arg in zip(self.slots.split(' '), args):
            setattr(self, slot, arg)

    def _info(self):
        return tuple(getattr(self, attr) for attr in self.slots.split())

    def __eq__(self, other):
        return self._info() == other._info()

    def __hash__(self):
        return hash((type(self), self._info()))


class Account(Slottable):
    slots = "first last age id balance"

    def fullname(self):
        return self.first + " " + self.last

matt = Account("Matthew", "Smith", 28, 666, 1E6)
john = Account("John", "Jones", 46, 667, 1E7)

d = {matt: 5, john: 6}  # Hashable

print matt.fullname()
#=> "Matthew Smith"
print john.fullname()
#=> "John Jones"
print matt == matt, matt == john
#=> True False
matt.age = 29  # Happy birthday!
print matt.age
#=> 29

标签:oop,metaprogramming,python
来源: https://codeday.me/bug/20191030/1970493.html