How to override the `is` operator

Possible duplicate:
python: class override "is" behavior

I am trying to override the operator isso that I can do something like

if tom is writer:
   print 'tom is writing'
elif tom is programmer:
   print 'tom is programming'

Is this possible in python?

+3
source share
2 answers

As far as I know, you cannot override 'is' because it checks to see if two objects are the same object by comparing their memory addresses (e.g. pointer comparisons). You probably want to override '==' by implementing the tom method __eq__.

+4
source

Python isinstance, isinstance(tom,Writer).

, , , . , , , isinstance:

class Worker(object):
    def __init__(self, name):
        self.name = name

    def is_doing(self):
        return "working"

class Writer(Worker):
    def is_doing(self):
        return "writing"

class Programmer(Worker):
    def is_doing(self):
        return "programming"

workers = [
    Writer("Tom"),
    Programmer("Dick"),
    ]

for w in workers:
    print "%s is %s" % (w.name, w.is_doing())

Tom is writing
Dick is programming

Worker is_doing, .

O-O, Python Worker - , is_doing name, :

class Fish(object):
    def __init__(self, n):
        self.name = n
    def is_doing(self):
        return "swimming"

workers.append(Fish("Wanda"))

for w in workers:
    print "%s is %s" % (w.name, w.is_doing())

:

Tom is writing
Dick is programming
Wanda is swimming
+3

Source: https://habr.com/ru/post/1774432/


All Articles