python: class override “is” behavior

前端 未结 4 1438
遇见更好的自我
遇见更好的自我 2020-11-27 22:30

I\'m writing a class which encapsulates any arbitrary object, including simple types. I want the \"is\" keyword to operate on the encapsulated value, such as this behavior:<

相关标签:
4条回答
  • 2020-11-27 23:15

    is itself cannot be overloaded, but you may be interested in other "Reflection" magic methods which may be suitable for your use case (since you are looking at this thread):

    __instancecheck__(self, instance) Checks if an instance is an instance of the class you defined (e.g. isinstance(instance, class).

    __subclasscheck__(self, subclass) Checks if a class subclasses the class you defined (e.g. issubclass(subclass, class)).

    0 讨论(0)
  • 2020-11-27 23:26

    Generally, if you want to test equality in terms of value (if x is 1, or True, or None), you'd use the == operator anyway. If you want to use the is operator, you're generally testing if something is referring to something else, like list1 is list2.

    If you want to define special behavior for ==, you can define __eq__ in your class definition.

    0 讨论(0)
  • 2020-11-27 23:26

    No. is, and, and or cannot be overloaded.

    Indeed. I believe that keywords are reserved and cannot be overloaded or changed.

    See: http://docs.python.org/2/reference/lexical_analysis.html#keywords

    "The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers."

    The list is: ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

    This list can be viewed through the command

    keyword.kwlist

    (Don't forget to import keyword first)

    Also:

    keyword.iskeyword('is')

    Returns True


    Update:

    My answer was bad and I should feel bad.

    I've messed with del myself. I don't know why I didn't notice that...

    2nd try:

    The following documentation provides a full list of customizable behavior on classes. This includes all the methods for overriding and overloading operators. 'is' is not included.

    http://docs.python.org/2/reference/datamodel.html#special-method-names

    Best I can do.

    0 讨论(0)
  • 2020-11-27 23:27

    No. is, and, and or cannot be overloaded.

    0 讨论(0)
提交回复
热议问题