2011-07-15 17 views
1

我想要做這樣的事情:python:我可以用一個類的getter方法使用字符串格式化運算符嗎?

class Foo(object): 
    def __init__(self, name): 
     self._name = name 
     self._count = 0 
    def getName(self): 
     return self._name 
    name = property(getName) 
    def getCount(self): 
     c = self._count 
     self._count += 1 
     return c 
    count = property(getCount) 
    def __repr__(self): 
     return "Foo %(name)s count=%(count)d" % self.__dict__ 

但是,這並不工作,因爲namecount與干將性能。

有沒有辦法解決這個問題,所以我可以使用帶有命名參數的格式字符串來使getter被調用?

回答

2

只是將其更改爲不使用self.__dict__。您有權訪問namecount爲屬性,而不是試圖通過他們的屬性綁定到的名稱來訪問它們:

class Foo(object): 
    def __init__(self, name): 
     self._name = name 
     self._count = 0 
    def getName(self): 
     return self._name 
    name = property(getName) 
    def getCount(self): 
     c = self._count 
     self._count += 1 
     return c 
    count = property(getCount) 
    def __repr__(self): 
     return "Foo %s count=%d" % (self.name, self.count) 

然後使用:

>>> f = Foo("name") 
>>> repr(f) 
'Foo name count=0' 
>>> repr(f) 
'Foo name count=1' 
>>> repr(f) 
'Foo name count=2' 

編輯:您仍然可以使用命名格式,但你必須改變你的方法,因爲你不能通過你想要的名字訪問屬性:

def __repr__(self): 
    return "Foo %(name)s count=%(count)d" % {'name': self.name, 'count': self.count} 

可能如果你重複的事情和/或有很多事情會更好,但它有點愚蠢。

+0

我知道我可以這樣做,但我寧願在格式化字符串中使用命名參數。我有一個情況,其中有6個或7個字段而不是2個,並且讓一個列表和一個格式化字符串保持同步是令人困惑的。 –

+0

@Jason是的,不幸的是沒有一個好的方法來做到這一點,如果你想通過名字'name'和'count'訪問它們,你必須以這種方式訪問​​屬性。我添加了一種愚蠢的方式,你可以用靜態名稱格式化,這可能會更好地滿足你的需求,但它可能不會。 –

+0

+1:這有點暴躁(或你說的「愚蠢」),但很直接。謝謝! –

相關問題