简体   繁体   中英

printing variable inside a def, inside a class

I am new to object oriented programming, what I want to do basically is print a variable inside a def which is in its turn inside a class, I think there's probably a very simple answer but I just can't figure it out, thanks for the assistance, here's my code:

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

this gives me the 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 I 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'

You can't do what you want; local variables only exist during the lifetime of a function call . They are not attributes of the function nor are they available outside of the call in any other way. They are created when you call the function, destroyed again when the function exits.

You can set attributes on function objects, but those are independent of locals:

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

If you need to keep a value a function produced, either return the value, or assign it to something that lasts longer than the function. Attributes on the instance are a common place to keep things:

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

If you want to print that value you could also use a return statement and the self parameter.

    class test():
        def test2(self):
            x = 12
            return x


     test = test()
     print(test.test2())

I do not know if this fully answers your questions but it is a way to print your x.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM