I am from Java background. I am going through the official Python tutorials but can’t seem to find the information in relation to Python source file names and classes.
In Java, file name is the same as main class name plus the .java extension. In Python what’s the case? In the examples of official tutorials, they are writing multiple classes and there’s no mention of the file name. I am kind of lost.
I have a file name called test_pie.py. The content is-
class ListTest:
list1 = [2, 'a', 'ab', 'c', 'aa', 0]
list2 = ['b', list1[-2:-5]]
def PrintList(self):
print list1
print list2
For list1 and list2: I get-
Undefined variable: list1
list Found at: test_pie
Undefined variable: list2
list Found at: test_pie
There’s a file. Period. Whatever is contained in it is of no interest for imports, and the file name or location doesn’t have any effect on the contained code (generally – it is accessible during execution, so some metaprogramming makes use of it but should be agnostic w.r.t. the actual value).
The contents of a file are not restricted to a single class, and few people impose such a restriction onto themselves. Python isn’t exclusively an OO language, you can and should have free functions whenever it’s sensible, and modules are seen one level above classes in code organizations – if several classes are closely related, they should propably go in one module.
Your example code/problem is unrelated to this, it’s a matter of scoping inside a given file. Classes do have their own scope, but you can’t and shouldn’t be using the class variables of the containing class in methods like this (directly) – it would make the code oblivious to a new value set in a subclass. Instead, you either use class methods (by the way, you should propably read http://dirtsimple.org/2004/12/python-is-not-java.html) or make use of the fact that instances inherit all members of the class and just prefix it with
self..