I'm trying to use UUID4 to create an ID for each instance of a class, User, however each time I print the instance a new UUID is generated. I'd thought that the if statement would mean it's only generated once but this isn't the case. Any help/guidance will be much appreciated, thanks.
This is my first time posting so please let me know if i can improve the post or add more info.
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)
I've just tried your code without problems. You probably are executing your script many times over and getting different ID's because of that. Each time you run it, new instances will be created by your current Python session and those are totally independent from each other.
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}")