Tracing
Tracing

Reputation: 1

Python Modular Inheritance

I'm trying to do the following:

File 1:
  class x:
    def somefunc(self):
      # Some code
      ect...

File 2:
  import File 1
  # Inherits x
  class y(File1.x):
      # Some code
      ect...

But this raises an error:

"name 'x' is not defined"

Edit: Changed x to File1.x. Still not working

Upvotes: 0

Views: 46

Answers (2)

itsjeyd
itsjeyd

Reputation: 5280

You need to do from file1 import x or class y(file1.x) to make this work.

EDIT: Make sure you have no spaces in your file names. Maybe it's just a typo in your question, but at the top of File2 you are saying import File 1 instead of import File1. If the name of your Python module corresponding to File1 does indeed contain one or more spaces, you should remove them (or replace them with underscores), both in the file name and the import statement. As explained in the accepted answer to this question, file names are used as identifiers for imported modules, and Python identifiers can't contain spaces.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121584

You imported the module into your namespace; x is an attribute of the module:

import modulename

class y(modulename.x):

Alternatively, use the from modulename import syntax to bind objects from a module into your local namespace:

from modulename import x

class y(x):

Upvotes: 4

Related Questions