python: class override “is” behavior

前端 未结 4 1508
遇见更好的自我
遇见更好的自我 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: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.

提交回复
热议问题