w3resource

How do you define instance variables in a Python class?

Understanding instance variables in Python classes

In Python, instance variables are defined within the class using the 'self' keyword. The 'self' keyword refers to the current instance of the class, and it allows you to access and assign values to instance variables.

Usually, instance variables are defined in the '__init()__' method, also known as the constructor. The '__init()__' method is automatically called when an object is created and initializes instance variables with initial values.

Syntax: Define instance variables in a Python class

class MyClass:
    def __init__(self, arg1, arg2, arg3):
        self.instance_var1 = arg1
        self.instance_var2 = arg2
        self.instance_var3 = arg3

In the example above, we have a class "MyClass" with two instance variables: 'instance_var1' and 'instance_var2'. These variables are defined within the '__init()__' method using the 'self' keyword. When an object of "MyClass" is created, the '__init()__' method is automatically called, and the values passed as arguments ('arg1', 'arg2' and 'arg3') are used to initialize the instance variables.

Example: Here's how to create an object of MyClass and access its instance variables

class MyClass:
    def __init__(self, arg1, arg2, arg3):
        self.instance_var1 = arg1
        self.instance_var2 = arg2
        self.instance_var3 = arg3
        
# Create an object of MyClass
obj = MyClass("Nida Hristiyan", "USA", 42)

# Access instance variables
print(obj.instance_var1)  # Output: Nida Hristiyan
print(obj.instance_var2)  # Output: USA
print(obj.instance_var3)  # Output: 42

In the example above, 'obj' is an instance of 'MyClass' with instance_var1 set to "Nida Hristiyan", instance_var2 set to "USA" and instance_var3 set to 42. Each instance of the class will have its own separate copies of the instance variables, allowing objects to hold unique data and state.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-interview/how-do-you-define-instance-variables-in-a-python-class.php