python - printing variable inside a def, inside a class -


i new object oriented programming, want basicaly print variable inside def wich on turn inside class, think theres probaly simple answer cant figure out, assistance, heres code:

class test():     def test2():         x = 12 print(test.test2.x) 

this gives me following error:

traceback (most recent call last):   file "/home/vandeventer/x.py", line 4, in <module>     print(test.test2.x) attributeerror: 'function' object has no attribute 'x' 

when try:

class test():     def test2():         x = 12 print(test.x) 

i get:

traceback (most recent call last):   file "/home/vandeventer/x.py", line 4, in <module>     print(test.x) attributeerror: type object 'test' has no attribute 'x' 

any welcome

you can't want; local variables exist during lifetime of function call. not attributes of function nor available outside of call in other way. created when call function, destroyed again when function exits.

you can set attributes on function objects, independent of locals:

>>> class test(): ...     def test2(): ...         pass ...     test2.x = 12 ... >>> test.test2.x 12 

if need keep value function produced, either return value, or assign lasts longer function. attributes on instance common place keep things:

>>> class foo(): ...     def bar(self): ...         self.x = 12 ... >>> f = foo() >>> f.bar() >>> f.x 12 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -