Class attributes belong to the class itself and they will be shared by all the instances and hence contains same value of each instance. Such attributes are defined in the class body parts usually at the top, for legibility.
Suppose we have the following code snippet :
[1, 2, 3, 4] [1, 2, 3, 4]
It prints [1, 2, 3, 4] for x and [1, 2, 3, 4] for y. Suppose the output we want is [1, 3] for x and [2, 4] for y. We can get the desired output by the following ways:
Method #1: By declaring them inside the
Declaring the variables inside the class declaration makes them class members and not instance members. Declaring them inside the
__init__ method ensures that a new instance of the members is created alongside every new instance of the object, which is what we need.
[1, 3] [2, 4]
In the original code no value is assigned to list attribute after instantiation; so it remains a class attribute. Defining list inside
__init__ works because
__init__ is called after instantiation.
Method #2: By creating the new list and storing the values in that.
[1, 3] [2, 4]
- PYGLET – Getting font instances used in Formatted Document
- Python dictionary (Avoiding Mistakes)
- Python | Avoiding quotes while printing strings
- Shared Reference in Python
- Python | Common items among dictionaries
- Python | Bitwise OR among List elements
- Python | Common words among tuple strings
- Python | Index Maximum among Tuples
- Python - Diagonal element addition among lists
- Python - Count of matching elements among lists (Including duplicates)
- PyQt5 - Selecting any one check box among group of check boxes
- Python - Convert Tick-by-Tick data into OHLC (Open-High-Low-Close) Data
- Class or Static Variables in Python
- String Template Class in Python
- Changing Class Members in Python
- Object Oriented Programming in Python | Set 1 (Class, Object and Members)
- class method vs static method in Python
- First Class functions in Python
- Violinplot in Python using axes class of Matplotlib
- Class and Instance Attributes in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.