piglei / one-python-craftsman

来自一位 Pythonista 的编程经验分享,内容涵盖编码技巧、最佳实践与思维模式等方面。

Home Page:https://www.piglei.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

On Code in 10-a-good-player-know-the-rules.md

LordMoMA opened this issue · comments

The output:

 {<__main__.VisitRecord object at 0x7fb6e872d280>, <__main__.VisitRecord object at 0x7fb6e872d940>} 

is returned by the find_potential_customers_v3() function, not real data from:

# 去过普吉岛的人员数据
users_visited_phuket = [
    {"first_name": "Sirena", "last_name": "Gross", "phone_number": "650-568-0388", "date_visited": "2018-03-14"},
    {"first_name": "James", "last_name": "Ashcraft", "phone_number": "412-334-4380", "date_visited": "2014-09-16"},
    ... ...
]

# 去过新西兰的人员数据
users_visited_nz = [
    {"first_name": "Justin", "last_name": "Malcom", "phone_number": "267-282-1964", "date_visited": "2011-03-13"},
    {"first_name": "Albert", "last_name": "Potter", "phone_number": "702-249-3714", "date_visited": "2013-09-11"},
    ... ...
]

Do we need to add a repr method inside the class in order to print out the real data like:

def __repr__(self):
        return f"VisitRecord(first_name={self.first_name}, last_name={self.last_name}, phone_number={self.phone_number}, date_visited={self.date_visited})"

Or is there any intention of simply writing the class like:

class VisitRecord:

    def __init__(self, first_name, last_name, phone_number, date_visited):
        self.first_name = first_name
        self.last_name = last_name
        self.phone_number = phone_number
        self.date_visited = date_visited

    def __hash__(self):
        return hash(
            (self.first_name, self.last_name, self.phone_number)
        )

    def __eq__(self, other):
        if isinstance(other, VisitRecord) and hash(other) == hash(self):
            return True
        return False
commented

Yes, the code would have been better if the __repr__ method had been implemented in the find_potential_customers_v3() iteration. But when I was writing this topic, I thought that introducing the __repr__ method might increase the cognitive load for the reader, because it's another new dunder method that is not closely related to the topic and needs explanation (for example, "If __repr__, what about __str__?"). So I decided not to implement it.