defining a method that could be used as instance or static method
Gerard Flanagan
grflanagan at gmail.com
Mon Mar 10 12:07:19 EDT 2008
On Mar 10, 4:39 pm, Sam <samuel.pro... at gmail.com> 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.
>
> Sam
------------------------------------------------------
class MyClass(object):
'''
>>> a = MyClass(3)
>>> b = MyClass(4)
>>> c = MyClass(3)
>>> a.isequal(b)
False
>>> a.isequal(c)
True
>>> MyClass.comp(a, b)
False
>>> MyClass.comp(a, c)
True
'''
def __init__(self, val):
self.value = val
@staticmethod
def comp(a, b):
return a.value == b.value
def isequal(self, b):
return self.comp(self, b)
if __name__ == '__main__':
import doctest
options = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE
doctest.testmod(optionflags=options)
------------------------------------------------------
More information about the Python-list
mailing list