+ 5
Python class objects
How these two declarations are different? Can anyone explain with a clear example? 1. class ClassName: ObjName = xyz 2. class ClassName: def __init__(self): self.ObjName = xyz
8 Answers
+ 8
If you have multiple members of that class they will all share the same value for ObjName. If you use example 2 however, you can modify the ObjName for a specific object without changing the value for the other objects
+ 3
Zoetic_Zeel ╰☆☆ S͎p͎e͎a͎r͎y͎ ☆☆╮ I realised that zoetic has already given us the example of Speary which is a good example, I just didn't realise it untill now. When you look at the code, when b.ObjName is changed, the ObjName of a is also changed as it is treated as a regular variable. There are cases where you wouldn't want that, because you might want ObjName to be different for every member. In that case, you should use self
+ 2
Julian Lachlan Actually ╰☆☆ S͎p͎e͎a͎r͎y͎ ☆☆╮ tried it here but when we declare it in same way, they functions the same. I don't see any difference here
https://code.sololearn.com/cjJpXYh1isk5/?ref=app
+ 2
Zoetic_Zeel this wasn't exactly how i ment it. I ment it in the way that if you have multiple members of the same class, you should use self else objName would be a variable that is the same for every member as it is a variable which isn't assigned to a specific member
+ 2
Hello Julian, can you kindly illustrate with an example code so that we can learn something from it?
+ 2
Julian ╰☆☆ S͎p͎e͎a͎r͎y͎ ☆☆╮ It is changed because in that example in block 1, a & b are not instances of class, they are the class itself, if we declare without parentheses. So they are sharing same values
+ 1
Yes correct, in the first example, the value of "ObjName is shared among all objects you create from that class whereas in the second example each object had a unique attribute called "ObjName" that you can change for each object.
+ 1
Julian ╰☆☆ S͎p͎e͎a͎r͎y͎ ☆☆╮ Here I am changing the value of one instance and it's not reflecting over other one.
https://code.sololearn.com/cuLYbS2anCu0/?ref=app