defining a method that could be used as instance or static method

Diez B. Roggisch deets at nospam.web.de
Mon Mar 10 11:58:33 EDT 2008


Sam wrote:

> Hello
> 
> I would like to implement some kind of comparator, that could be
> called as instance method, or static method. Here is a trivial pseudo
> code of what I would like to execute
> 
>>> class MyClass:
> ...    def __init__(self, value):
> ...        self.value = value
> ...    def comp(self, compValue):
> ...        return self.value == compValue.value
>>> a = MyClass(3)
>>> b = MyClass(4)
>>> c = MyClass(3)
>>> a.comp(b)
> False
>>> a.comp(c)
> True
> 
> This is actually achieved by MyClass, how could implement it in order
> to accept:
> 
>>> MyClass.comp(a, b)
> False
> 
> I would really appreciate a pointer or a way to complete MyClass in
> order to fulfill my requirements. Thank you for your attention.

Did you try that it doesn't work? because it should. Whenever you do

instance.method(arg, ..)

you can as well do

Class.method(instance, arg, ...)

so your requirement should be met by comp already.

Diez



More information about the Python-list mailing list