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

AbotX : How do you create a parallel crawler that stays on and can be added to at run time from new requests -

testing - Detect whether test has failed within fixture -

android - Create single AAR file from multiple modules using Gradle -