How to compare two instances of an object Python?

python compare objects in list
python class comparison
python compare object attributes
python check if two objects are equal
python compare strings
python __eq__ method example
python compare dictionaries
python rich comparison

Attempting to compare two objects' data members; however, the error message has no specific details, which leaves me with little information on how to go about correcting it

class Person: 
  def __init__(self, name, age, id):
    self.name = name
    self.age = age
    self.id = id

  def same_person(Person lhs, Person rhs):
    return lhs.id == rhs.id

person1 = Person("David Joyner", 30, 901234567)
person2 = Person("D. Joyner", 29, 901234567)
person3 = Person("David Joyner", 30, 903987654)
# print calls provided as part of an exercise: not my implementation
print(same_person(person1, person2))
print(same_person(person1, person3))
  • Python 3.6.5
  • Command: python person.py
  • Error message
  • If it were an indentation level the following error is displayed

The other answers are correct and provide the best way to do it, but I realized that you wrote:

print calls provided as part of an exercise: not my implementation

print(same_person(person1, person2))
print(same_person(person1, person3))

The exercise probably wants you to define a function outside the class. You can do that by removing that function from the class and writing it un-indented outside the class (without providing class type too). For example:

class Person: 
    def __init__(self, name, age, id):
        self.name = name
        self.age = age
        self.id = id

def same_person(lhs, rhs):
    return lhs.id == rhs.id

person1 = Person("David Joyner", 30, 901234567)
person2 = Person("D. Joyner", 29, 901234567)
person3 = Person("David Joyner", 30, 903987654)

print(same_person(person1, person2))
print(same_person(person1, person3))

Compare object instances for equality by their attributes, Both “is” and “==” are used for object comparison in Python. The operator “==” compares values of two objects, while “is” checks if two objects are same (In other  Set-Comparison Methods. We’ll go over six set methods in pairs of two at a time. Each method will have a description, a visual diagram, and a code example. Let’s get to it..union() and

same_person is a method of the class Person and should take just an argument as input. It should be defined as:

def same_person(self, other):
    return self.id == other.id

and called as

person1.same_person(person2)

or you could override the __eq__ method (i.e., ==).

def __eq__(self, other):
    return self.id == other.id

in order to be able to do it as person1 == person2

Python Object Comparison : "is" vs "==", It's easy to compare Python built-in objects, like 1 < 2, 'abc' < 'abd', tuple (0, 1, 3) < tuple (0, 2, 1). But how to compare your own objects? Say we have a Point  The Python is and is not operators compare the identity of two objects. In CPython, this is their memory address. Everything in Python is an object, and each object is stored at a specific memory location. The Python is and is not operators check whether two variables refer to the same object in memory.

class Person: 
   def __init__(self, name, age, id):
      self.name = name
      self.age = age
      self.id = id

   def same_person(self, lhs, rhs):
      return lhs.id == rhs.id

you dont have to define lhs and rhs type in python unless you are using typings.

How to compare/sort Python objects? - Chao Ren, In Python 2, __cmp__(self, other) implemented comparison between two objects, returning a negative value if self < other , positive if self > other , and zero if they  Both “is” and “==” are used for object comparison in Python. The operator “==” compares values of two objects, while “is” checks if two objects are same (In other words two references to same object).

Quite a few mistakes:

  1. The arguments in the method cannot be preceded by the Person classname
  2. You have not defined instances person1, person2 and person3
  3. If you define an instance method (same_person), it should be used ON an instance.

This is what I would do:

class Person:
    def __init__(self, name, age, id):
        self.name = name
        self.age = age
        self.id = id

    def same_person(self, other):
        return self.id == other.id

person1 = Person("Bob", 25, 1)
person2 = Person("Mike", 33, 1)
person3 = Person("Maria", 28, 2)

print(person1.same_person(person2))
print(person1.same_person(person3))

Output:

True
False

Comparing and Sorting, Python has two very similar comparison operators: == for equality andis for object identity. Typically, is faster, as the implementationjust needs  Comparing and Sorting¶ Python 3 is strict when comparing objects of disparate types. It also drops cmp-based comparison and sorting in favor of rich comparisons and key-based sorting, modern alternatives that have been available at least since Python 2.4. Details and porting strategies follow.

Identical Objects Do Not Imply Equality In Python, A common mistake in Python 2 was to override only __eq__() and Hashable objects which compare equal must have the same hash value. I need to compare 2 instances of objects to see whether they are equal or not, but with the code down it does not work (it outputs "not equal") #!/usr/bin/python class Test: var1 = '' var2 = '' Take care, this creates two *class* variables var1 and var2. For *instance* variables, you want: class Test: def __init__(self, var1='', var2=''): self

Python Hashes and Equality · Homepage of Hynek Schlawack, Your comment asks specifically about Python, but in any language the best way to test two objects for equality is to test each attribute. if you compare object  Introduction. Object-oriented programming allows for variables to be used at the class level or the instance level. Variables are essentially symbols that stand in for a value you’re using in a program. At the class level, variables are referred to as class variables, whereas variables at the instance level are called instance variables.

How to test if two objects are equal if I defined the class, Python tries to re-use objects in memory that have the same value, which also makes comparing objects Python has the two comparison operators == and is . Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. To create a class, use the keyword class: Create a class named MyClass, with a property named x: Try it Yourself »

Comments
  • Among other things, you are probably mixing tabs and spaces in your indentation somewhere.
  • Much appreciated
  • Glad to help :-)
  • @aguilar keep in mind that the best way to compare two objects would be overriding __eq__() method of the class, have a look at this
  • return self is other is a bit more elegant.
  • @DYZ: but then Person(1, 2, 3) != Person(1, 2, 3), since they're not the same object.
  • If you suggest to add self.id is other.id I don't really understand why, we are checking equality not object identity.
  • I suggest to replace self.id == other.id with self is other (both expressions are fully equivalent).