Animal class, we have defined
is_alive as a class variable by assigning it a value outside all the methods. That variable is shared by all instances of
One technique, among several, for accessing it is to refer to it as
Animal.is_alive. This can be done in a local or global context, even if no instances of the class have been created.
If we change the value of the class variable
is_alive, it is changed for all instances, since there is only one copy of it.
We can create an instance variable with the same name. If, within some method,
self refers to the current instance, this will either create an
is_alive instance variable or change its value if it already exists …
self.is_alive = False
You can even have a local variable by the same name, either by using it as the name of a method parameter, or performing an assignment within a method without dot notation, as follows …
is_alive = False
Be careful with the above. If you have several variables with the same name, it is easy to make mistakes, resulting in buggy code.
Validating the values of arguments passed to functions or methods is a good practice, and @mtf has demonstrated a good way of doing it with a
ValueError. In fact, once you have verified that an argument has a valid type, you can check for acceptable values of that type and raise a
ValueError if an unacceptable value has been passed. For example, in some situations, you may want to reject negative numbers even if an argument is of the correct type. An
Animal cannot have a negative number of legs.
See the following for lots of Python 3 documentation on this topic …