Hướng dẫn __gt__ python
Short summary: Syntax
To use the greater than operator on custom objects, define the
The method should return a Boolean Let’s have a look at an example next. ExampleIn the following code, you compare two persons with each other by using the class Person: def __init__(self, age): self.age = age def __gt__(self, other): return self.age > other.age alice = Person(18) bob = Person(17) carl = Person(18) print(alice > bob) # True print(alice > carl) # False print(bob > alice) # False For example, because Alice’s age is 18 years and Bob’s 17 years, the expression Background VideoPython Greater Than Default Implementation of __gt__The class Person: def __init__(self, age): self.age = age alice = Person(18) bob = Person(17) carl = Person(18) print(alice > bob) Traceback (most recent call last): File "C:\Users\...\code.py", line 10, in TypeError: ‘>’ not supported between instances of ‘…’ and ‘…’If you get the class Finxter: pass x = Finxter() y = Finxter() x > y # Python will raise an error! Output: Traceback (most recent call last): File "C:\...\code.py", line 8, in To fix the error, simply define the class Finxter: def __gt__(self, other): return 42 x = Finxter() y = Finxter() x > y # Now it works! # 42 Commutativity of Greater Than >The output of You can see this in the following example: class Person: def __gt__(self, other): return False class Human: def __gt__(self, other): return True alice = Person() bob = Human() print(alice > bob) # False print(bob > alice) # True Programming Humor💡 Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science. ~~~
Feel free to check out our blog article with more coding jokes. 😉 While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students. To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide. His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here. |