每次打印实例时,我的实例变量 ID 都会发生变化。我写的 if 语句没有解决它。包括代码

My instance variable ID is changing each time I print the instance. The if statement I've written doesn't fix it. Code included

我正在尝试使用 UUID4 为 class 用户的每个实例创建一个 ID,但是每次我打印该实例时都会生成一个新的 UUID。我以为 if 语句意味着它只生成一次,但事实并非如此。任何 help/guidance 将不胜感激,谢谢。

这是我第一次 post 如果我可以改进 post 或添加更多信息,请告诉我。

class User:

    def __init__(self) -> None:
        self.user_id = None
        self.auth_key =  None

        if self.user_id == None: self.user_id = uuid4()

    def __repr__(self) -> str:
        return f"""User ID: {self.user_id}
        Authorisation Key: {self.auth_key}"""

new_user = User()

print(new_user)

我刚刚尝试了您的代码,没有出现任何问题。您可能会多次执行脚本并因此获得不同的 ID。每次您 运行 它时,您当前的 Python 会话都会创建新实例,并且这些实例彼此完全独立。

from uuid import uuid4

class User:

    def __init__(self) -> None:
        self.user_id = uuid4()
        self.auth_key =  None

    def __repr__(self) -> str:
        return f"User ID: {self.user_id}\nAuthorization Key: {self.auth_key}"
    
    def __eq__(self, other):
        return self.user_id == other.user_id

new_user = User()

# Same instance on same session:
print(new_user)
print(new_user)
print(new_user)

# Different instance on same session:
another_user = User()

# Comparing them:
print(f"new_user: {new_user.user_id}")
print(f"another_user: {another_user.user_id}")

# Identity test:
print(f"new_user is new_user: {new_user is new_user}")
print(f"new_user is another_user: {new_user is another_user}")