Do You Really Need That Instance Variable? // Python Tips

preview_player
Показать описание


#arjancodes #softwaredesign #python
Рекомендации по теме
Комментарии
Автор

There is an important bug in that code.

This is when assigning the output of "random.randint" function into "answer". This call will only be done when importing the code, being this "answer" constant for all the instances of the dataclass created in the same Python execution. All of the instances will share the same "answer" value, meaning it will be not random :)

Better to use the "default_factory" keyword argument from "field" in dataclasses to call a function whenever each instance of the dataclass is created.
I hope I am not wrong!

Side comment: Thanks for all these videos. They are always so enjoyable to see and they bring some different value compared to other ones that can be seen here! Learned lots from there

IManuI
Автор

In that example program, it seems to me that the whole NumbersGame class is unnecessary, since there's never more than one instance of it, and there are only two class variables. I'd love to hear your opinion about when it is or isn't appropriate to use a class. I've seen other videos excoriating the excess use of classes--I wonder if you agree. Thanks!

kenhaley
Автор

Isn't this a class attribute, not an instance attribute? And hence shared between all instances?

razean
Автор

Well, say you wanted to monitor the player's guesses for statistical analysis, then you would want it as an instance variable, so that some other function can access it. 🤫

malteplath
Автор

dataclass seems confusing, and not worth the shorter code

illuminatrix
Автор

guess = int(input('Guess a number'))
if guess == self.answer:
print('You win')
return True

print('Too low!' if guess < self.answer else 'Too high')
return False

abhishekscript