在Python3中,可以通過兩種方式調用實例方法,即obj.ix()
或Foo.ix(obj)
。撇開它是否是個好主意:當使用後者時,是否有辦法讓實例方法被訪問的類通過?調用unbound方法,獲取它通過訪問的類?
class Foo(object):
@classmethod
def cx(cls, obj):
print(cls.X)
def ix(self):
# Any way to get the class that ix was accessed through?
print(self.X)
class AFoo(Foo):
X = "A"
class BFoo(Foo):
X = "B"
a = AFoo()
AFoo.cx(a) # Prints "A"
AFoo.ix(a) # Prints "A"
b = BFoo()
BFoo.cx(b) # Prints "B"
BFoo.ix(b) # Prints "B"
AFoo.cx(b) # Prints "A"
AFoo.ix(b) # Prints "B" -> I would like "A", like classmethod.
BFoo.cx(a) # Prints "B"
BFoo.ix(a) # Prints "A" -> I would like "B", like classmethod.
正如你所看到的,所期望的行爲是微不足道的實現與一個類的方法,但似乎沒有成爲一個方式做同樣的一個實例方法。
很有意思,謝謝!似乎有不止一種方式去做,但這絕對是一個有效的答案,所以我接受了它。 – kloffy