To fix this, you can modify the _eq_ method to check if the object is an instance of the Person class before accessing the age attribute. It returns an error: AttributeError: 'int' object has no attribute 'age' Code language: JavaScript ( javascript ) Print(john = 20) Code language: PHP ( php ) The following compares a Person object with an integer: john = Person( 'John', 'Doe', 25) Print(john = mary) # False Code language: Python ( python ) Print(john = jane) # True Code language: Python ( python )Īnd if two instances of the Person class don’t have the same age, the = operator returns False: john = Person( 'John', 'Doe', 25) Now, if you compare two instances of the Person class with the same age, it returns True: john = Person( 'John', 'Doe', 25) The following shows how to implement the _eq_ method in the Person class that returns True if two person objects have the same age: class Person: def _init_ (self, first_name, last_name, age):ĭef _eq_ (self, other): return self.age = other.age Code language: Python ( python ) By default, Python uses the is operator if you don’t provide a specific implementation for the _eq_ method. Python Object-oriented programming (OOP) is based on the concept of objects, which can contain data and code: data in the form of instance variables (often known as attributes or properties), and code, in the form method. Python automatically calls the _eq_ method of a class when you use the = operator to compare the instances of the class. This Object-Oriented Programming (OOP) exercise aims to help you to learn and practice OOP concepts. To do it, you can implement the _eq_ dunder method in the Person class. In other words, you want the following expression to return True: john = jane Since john and jane have the same age, you want them to be equal. ![]() And you can check it using the is operator: print(john is jane) # False Code language: Python ( python )Īlso, when you compare john with jane using the equal operator (=), you’ll get the result of False: print(john = jane) # False Code language: Python ( python ) ![]() In this example, the john and jane objects are not the same object. Jane = Person( 'Jane', 'Doe', 25) Code language: Python ( python ) Self.age = age Code language: Python ( python )Īnd you create two instances of the Person class: john = Person( 'John', 'Doe', 25) Suppose that you have the following Person class with three instance attributes: first_name, last_name, and age: class Person: def _init_ (self, first_name, last_name, age): Summary: in this tutorial, you’ll learn how to use the Python _eq_ method to compare two objects by their values.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |