Home > Article > Backend Development > Here are a few question-based titles, tailored to your provided article content: Option 1 (Focus on Distinction): * How Does Python Differentiate Between Class Variables and Instance Variables? Opt
Understanding Python Class and Instance Variables
In Python, objects created from a class can possess two types of variables: class variables and instance variables. Class variables are shared among all instances of a class, while instance variables are unique to each instance.
Class Variables
Class variables are defined outside of the __init__ method. They are declared using the class name, followed by a dot and the variable name. For example:
<code class="python">class MyClass: class_variable = 100</code>
All instances of MyClass will have access to the class_variable.
Instance Variables
Instance variables are defined within the __init__ method. They are declared using the self keyword, followed by the variable name. For example:
<code class="python">class MyClass: def __init__(self): self.instance_variable = 200</code>
Each instance of MyClass will have its own unique instance_variable.
Example Clarification
Regarding the example mentioned in the question:
Advanced Example
The following example demonstrates a more complex scenario:
<code class="python">class MyClass: class_variable = ['foo'] def __init__(self): self.instance_variable = ['bar']</code>
In this example, class_variable is a class variable and instance_variable is an instance variable. When you access x.list, you are accessing the instance variable, which has been modified to contain 'thing'. When you access testClass.list, you are accessing the class variable, which remains unmodified.
The above is the detailed content of Here are a few question-based titles, tailored to your provided article content: Option 1 (Focus on Distinction): * How Does Python Differentiate Between Class Variables and Instance Variables? Opt. For more information, please follow other related articles on the PHP Chinese website!