当前位置: 动力学知识库 > 问答 > 编程问答 >

object - Python Modular Inheritence

问题描述:

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"

Any help?

Edit: Changed x to File1.x.

Still not working

网友答案:

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):
网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: