Python Variable Declaration
I want to clarify how variables are declared in Python.
I have seen variable declaration like this:
class writer:
path = ""
Sometimes, there is no explicit declaration, and variables are just initialized using __init__
:
def __init__(self, name):
self.name = name
I understand the purpose of __init__
, but is it advisable to declare variables in any other functions?
Also, how can I create a variable to hold a custom type in Python? For example:
class writer:
path = "" # string value
customObj = ?? # custom type?
Can you explain how to python declare variable in these contexts and whether it’s recommended to declare them in methods other than __init__
?
Hey All!
Hope you are doing great, Here is the detailed explanation of the above question:-
To start with, the most common and recommended way to declare variables in Python classes is by using the __init__
method. This method serves as the constructor for the class, and it gets called when an object is created. By declaring instance variables inside the __init__
method, you ensure they are tied to the object’s lifetime. Plus, it makes it easy to initialize them with different values as needed.
For example:
class Writer:
def __init__(self, name, custom_obj):
self.name = name
self.custom_obj = custom_obj # custom type variable
Here, name
and custom_obj
are instance variables tied to each object, and they form part of the class’s state.
Building on what @Rashmihasija said, if you need a variable that should be shared across all instances of the class, then it’s better to declare it as a class variable, outside of __init__
. Class variables are tied to the class itself, not any specific instance, meaning they are shared across all objects of that class.
For instance:
class Writer:
path = "" # Class variable, shared among all instances
custom_obj = None # Class variable for custom type, shared across all instances
Here, both path
and custom_obj
are class variables. They’re not tied to any single instance but are available across every instance of the Writer
class.
Hey,
Now, to add another perspective, you can also declare instance variables in methods other than __init__
. Though it’s not the most common approach, it can be useful in situations where the variable initialization depends on some logic that arises during the object’s lifecycle. Instead of setting the variable right in __init__
, you can set it later with a specific method.
For example:
class Writer:
def set_custom_obj(self, custom_obj):
self.custom_obj = custom_obj # Declared within another method
In this case, custom_obj
is initialized not during the object creation but when set_custom_obj
is called. This can be helpful if the initialization of the variable requires additional logic or conditional behavior that shouldn’t necessarily be part of the __init__
method.