Understanding how to import variables from a method

Let's say I have something like this: This is a tree.py file:

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

This is the view.py file:

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

How to get a subclass of a green form variable I know that a class is simple:

This is the tree.py file:

 class leaf(): x = 100 

This is the view.py file:

 from tree import leaf class view(): g = leaf() print gx 

I understand how to do this if both classes are in the same file. But I do not understand in two separate files. Thanks John

0
source share
2 answers

I think the root of your problem is that you need to learn more about how classes work in Python. Fortunately, the tutorial in 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 extremely helpful.

+2
source

x is local to the method, that is, it should not (and cannot, at least not easily) be accessed from outside. Worse - it exists only when the method starts (and is deleted after it is returned).

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

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

But this is probably not what you want (for starters, you cannot access it as a local variable inside the method - because it is not one) and actually very rarely useful (unless you have a really good reason, for, it's just use class).

+1
source

Source: https://habr.com/ru/post/1483678/


All Articles