3

私のクラスの多くは、アカウントを表す次のクラスのように見えます

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

しかし、実際に関連する情報は、私が気にかけている属性のリストだけですfirst, last, age, id, balance。この構造に従う Python クラスを定義する標準的な方法はありますか?

一見、私は考えnamedtupleましたが、事後に追加のメソッドを追加できるかどうかはわかりません。本当に、私は次のようなものが欲しい

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

    def ... # other methods

これを取得する最良の方法は何ですか?

4

3 に答える 3

4

それがどれほど慣用的なものかはわかりませんが、次のものが要件を満たしています。

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
于 2013-06-14T18:32:04.923 に答える