+ 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

5th Nov 2018, 8:15 AM
Zoetic_Zeel
Zoetic_Zeel - avatar
8 Antworten
+ 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
5th Nov 2018, 8:20 AM
Julian
Julian - avatar
+ 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
10th Nov 2018, 10:50 AM
Julian
Julian - avatar
+ 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
10th Nov 2018, 10:37 AM
Zoetic_Zeel
Zoetic_Zeel - avatar
+ 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
10th Nov 2018, 10:40 AM
Julian
Julian - avatar
+ 2
Hello Julian, can you kindly illustrate with an example code so that we can learn something from it?
10th Nov 2018, 10:42 AM
Gordon
Gordon - avatar
+ 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
10th Nov 2018, 10:52 AM
Zoetic_Zeel
Zoetic_Zeel - avatar
+ 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.
5th Nov 2018, 9:02 PM
Lachlan
+ 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
10th Nov 2018, 10:49 AM
Zoetic_Zeel
Zoetic_Zeel - avatar