[Tutor] Everything in one file?
steve at pearwood.info
Wed Jul 18 11:52:07 EDT 2018
On Wed, Jul 18, 2018 at 03:46:20PM +0200, Shall, Sydney wrote:
> On 24/05/2018 03:27, Steven D'Aprano wrote:
> > On Tue, May 22, 2018 at 03:46:50PM +0530, aishwarya selvaraj wrote:
> >> Dear all,
> >> I have created 2 classes in 2 separate files.
> > If you have learned the bad habit from Java of putting every class in a
> > separate file, you should unlearn that habit for your Python code. There
> > is no need to put every class in a separate file, and it usually leads
> > to complicated dependencies and circular imports.
> I am an slightly more than a beginner.
> I have not met this advice from Steven D'Aprano before, so I have some
Note that I said there is no *need* to put each class in a separate
file, not that one should "never" split classes into separate files.
> I have constructed a program which has a parent class and a child class
> and I have them in two different files. I import the parent class into
> the child class and create instances with the child class. This works fine.
> But, would it be better to have both classes in one file?
Even better, why do you have two classes if you only ever use one?
If Parent is never used on its own, and you only use Child, why bother
with Parent? Put everything into one class.
> Would then the
> child class 'know' that the parent class is in the file?
If you write this:
then it will work fine, for *exactly* the same reasons that this works:
x = 99
y = x + 1 # x is already defined
But if you try this instead:
# Stop! This won't work!
class Child(Parent): # NameError: unknown Parent
it won't work for exactly the same reason you can't write this:
y = x + 1 # NameError: unknown x
x = 99
> And further. I have a function which sets up all the suitable data
> structures into which this function will put the information supplied by
> the user. I import this file too into both the parent and the child class.
> Would the instances with which I actually work, 'know' that this
> function is there if it is simply present in the same file?
Every line of Python code "knows" whatever variables and names exist at
the moment that line of code is executed. That usually means variables,
classes and functions which are defined *above* it in the file.
Whether those variables are defined in place:
x = 99
or imported from somewhere else:
from module import x
makes no difference.
More information about the Tutor