First, as was pointed out in comments, you should declare variables in __init__
constructor. As to your example, I'd suggest to make some more advanced steps, so consider following: you actually have only one important variable, which is self.age
. Everything else is derived from it, and so you can lose consistency: for example, when changing self.age
another variables will not be changed. Also, you can later on in your project change self.seconds
variable, thus completely messing up your class instance. To solve that, have a look at property
decorator:
class ClassTester:
def __init__(self, age=10):
self.age = age
@property
def seconds(self):
return self.age * 365 * 24 * 60 * 60
@property
def msg(self):
return "You have lived for {} seconds.".format(self.seconds)
There, @property
is a handy decorator, which allows you to do address seconds
and msg
as attributes, but which will be always synced and consistent: first, you cannot set seconds
attribute, thus it is protected. Second, changing age
will affect all subsequent calls to msg
and seconds
.
Example usage:
>>> tester = ClassTester()
>>> tester.seconds
315360000
>>> tester.msg
'You have lived for 315360000 seconds.'
>>> tester.age = 23
>>> tester.seconds
725328000
>>> tester.msg
There is a lot more about @property
, feel free to explore! For example, see this answer for some in-depth @property
analysis.