Python objects compared to .NET objects

前端 未结 2 800
无人共我
无人共我 2021-01-27 01:38

I\'m very comfortable with .NET objects and its framework for reference vs value types. How do python objects compare to .NET objects? Specifically, I\'m wondering about equalit

相关标签:
2条回答
  • 2021-01-27 01:52

    Equality

    : - An object with no __cmp__ or __eq__ method defined will raise an error if you try to compare it inherits its comparisons from the object object. This means that doing a > b is equivalent to doing id(a) > id(b).

    The is keyword is also used to see if two variables point to the same object. The == operator on the other hand, calls the __cmp__ or __eq__ method of the object it is comparing.

    Hashability

    : - An object is hashable if there is a __hash__ method defined for it. All of the basic data types (including strings and tuples) have hash functions defined for them. If there is no __hash__ method defined for a class, that class will inherit it's hash from the object object.

    Copying

    : - copy, copy.deepcopy, and their respective in class methods __copy__ and __deepcopy__. Use copy to copy a single object, deepcopy to copy a heirarchy of objects. deepcopy

    Edits made at the suggestion of agf.

    0 讨论(0)
  • 2021-01-27 01:53

    In python you can define the __eq__ method to handle the == operator.

    The is operator checks if one object is the same as the other. (or more specifically two variables that reference one or two objects)

    >>> a = [1, 2, 3]
    >>> b = [1, 2, 3]
    >>> a == b
    True
    >>> a is b
    False
    >>> c = a
    >>> c is a
    True
    

    Now, this example uses the list type, which you can think of as a class which defines an __eq__ method that compares equality of all its items.

    Same for hash, you define a __hash__ method in your class that returns an integer that would identify your object. This is also available in the basic types that support hashing. See the hash function.

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