0

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

2
  • 1
    I don't think you understand how to use classes in Python. Commented Jan 26, 2011 at 17:25
  • 1
    Terminology mixup: A subclass of a class C is a class that inherits from C. A def inside a class is a method. Commented Jan 26, 2011 at 17:26

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

i have been through that doc. I am still rather confused.
@John I've added another link that you might find helpful. Do you have any prior experience with object-oriented programming>
Yeah with Java. Its much easier with Java it seems. All right then i'll check out that PDF. Thanks
@John it's not easier I'd say, just a bit different. In Python, all instance methods (non-static in Java terms) must take self as their first argument (which is the instance), and instance variables are referred to from within the class as self.var
@John you can use from other_module import SomeClass. You cannot import methods, for that you should just write a function outside a class.
|
1

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).

1 Comment

Your Correct. Thanks knowing you cant access the variable changed everything. I figure out how i wanted to do this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.