开发者

understanding how to Import variables from a method

Lets say i have something like this: This is file tree.py:

class leaf():
def green():
    x = 100

This is file view.py:

from tree import leaf.green 
g = green()
print g.x

How do i get the variable form subclass green I know for class its just:

This is file tree.py:

class leaf():

    x = 100

This is file view.py:

from tree import leaf 
class 开发者_高级运维view():
 g = leaf()
 print g.x

I understand how to do it if both classes are in the same file. But i dont understand in two seprate files. Thanks, John


I think the root of your problem is that you need to learn more about how classes in Python work. Fortunately, the tutorial in the Python docs has a section on classes.

If that doesn't help, going through something like Learn Python the Hard Way and doing the exercises can be immensely helpful.


x is local to the method, i.e. it shouldn't (and can't, at least not easily) be accessed from the outside. Worse - it only exists while the method runs (and is removed after it returns).

Note that you can assign an attribute to a method (to any function, really):

class Leaf(object):
    def green(self):
        ...
    green.x = 100

print Leaf.green.x

But that's propably not what you want (for starters, you can't access it as a local variable inside the method - because it isn't one) and in fact very rarely useful (unless you have a really good reason not to, just use a class).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜