user1234440
user1234440

Reputation: 23567

Class Referencing

I have two files: class1.py and class2.py

In the file class2.py I have a class that requires me to inherit a class in class1.py:

In file class2.py I have the following import function

import class1 as class1   #is the right way to do it?

My question is do I need to define the class like this:

class temp(class1):
    ...

or like this:

class temp(class1.class1)
    ...

Upvotes: 0

Views: 59

Answers (3)

Arun Reddy
Arun Reddy

Reputation: 3733

As you want to import a class which is itself lying in class1.py you need to use the second method - but as far as your code says there is a class called class1 in class1.py- if this is correct then go for second method. 'as' in import just makes it easy to use lengthy class names as shorter ones or to differentiate between any similar imported class names. So that wouldn't make much difference.

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

Don't give the file the same name of a class inside it, or Python won't know which one you want to refer to. You can call the file class1_file.py. Then when importing:

import class1_file as c1

and then use class1 as:

class temp(c1.class1):
    ...

Upvotes: 1

mgilson
mgilson

Reputation: 309861

You need the second form.

class temp(class1.class1):
   ...

With how you've import class1, in your class2 module, class1 is a reference to the class1 module which holds the class1 class.

The alternative is to only import the class1 class from the class1 module:

from class1 import class1

class temp(class1):
    ...

In general, to avoid these problems, you're best bet is to follow PEP 8 naming conventions -- Classes should be written as UppCaseWords, modules should use names_with_underscores.

Upvotes: 1

Related Questions