0

Class Question in Python

Input: class A: x = 0 def func(obj): obj.x = 2 return obj a = A() a.x = 1 b = func(a) print(a.x) output: 2 Can some one walk me through this code? I guess I am also a bit confused when a object takes an attribute defined value from the class itself vs. when that object is given an assigned value for the attribute outside the class. When does it take what value? (I.e. taking the value 2 instead of the value of 1)

15th May 2018, 12:04 PM
stephanie
stephanie - avatar
2 odpowiedzi
+ 3
You have instantiated an object of class A. The instance of the class starts with its attribute x set to 0. You then set that object's attribute to 1. You pass that object to a function which modifies the attribute again and then you print it. The attribute x belongs to that instance of A, so each time you perform a.x = y, that instance's x attribute is updated. So by the end of this code, you have an object of type A that has an x attribute with the value 2. Hope that helps
15th May 2018, 12:50 PM
Josh
Josh - avatar
0
So much help! Thank you!
16th May 2018, 1:37 PM
stephanie
stephanie - avatar