+ 1

If I want to print b of 5th line then What to write in last line's print statement?

class Cat: def __init__(self, color, legs): self.color = color self.legs = legs b=23 felix = Cat("ginger", 4) print(felix.color) print(?)

22nd Dec 2018, 9:04 AM
Kushang
Kushang - avatar
4 Respostas
+ 7
I found this ( http://code.activestate.com/recipes/577283-decorator-to-expose-local-variables-of-a-function-/ ) at Stack Overflow and edited it to keep function attributes (like __doc__). It looks bad but it's working I think https://code.sololearn.com/c8P9onZ2QjqE/?ref=app
22nd Dec 2018, 9:01 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 6
This is probably not 100% correct, but because of the missing "self.", b would be a class variable (instead of an instance variable), but b is within __init__(self) which is only called when you create an actual Cat object. This is contradictory. Usually you have to initialize a class variable outside of __init__(self): class Cat: x = 42 # class variable def __init__(self, color, legs): self.color = color self.legs = legs b = 23 # fake class variable print(Cat.x) # access class variable without creating a Cat object felix = Cat("ginger", 4) print(felix.__class__.x) # access class variable after creating a Cat object Paging Mert Yazıcı and Kishalaya Saha, please halp
22nd Dec 2018, 9:21 AM
Anna
Anna - avatar
+ 3
I don't usually code with classes, so I may be wrong. Mert is the right person to ask. But I don't think we can access b that way, just like we can't access a local variable outside the function where it's defined. Of course, we can add a "global b" inside __init__(), and then print(b) later, but that sort of defeats the purpose.
22nd Dec 2018, 9:51 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
Try to see a nornal function definition without class def func(): b = 23 a = 34 return a Can you print b or a here? You can print a after you assign it to a variable while calling func but you cant print a or b directly with print(a) or print(b) as they are defined in the local scope of function. Similarly in your example b is a local variable of __init__ function and cant be called directly outside, when you do self.b = 23 its assigned to that instance of class, like felix here, also it will help if you tell what were you trying to do and why you need to do that, as i cant seem to think how would printing b like that benefit rather than assigning it to self.b?
22nd Dec 2018, 10:06 AM
Mayank
Mayank - avatar