无法实例化在子目录中定义的类 [英] Unable to instantiate a class defined in a subdirectory

查看:87
本文介绍了无法实例化在子目录中定义的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的(简化的)项目布局如下:

  / __ init__.py 
/test.py
/lib/__init__.py
/lib/client.py

my test.py 只是:

  import lib.client 
A = client()
A.Test()

和我的 lib \client.py 开头如下:

  import ui# lib dir)

class client(object):

(Blah)

UI = None
b $ b def __init __():
UI = ui()

def Test():
printSuccess
/ pre>

当我尝试运行test.py时,我可以进入代码,看到客户端中的定义被解析,但是,当我到达行我实例化一个客户端,我得到以下异常:

  NameError:name'client'未定义



如果我将该行更改为:

  A = lib.client()

b
$ b

 'module'对象不可调用

我缺少什么?

解决方案

lib.client object import lib.client 是模块,而不是类。要实例化类,你需要调用模块对象中的类:



A = lib.client.client()



或者,如@rantanplan所说,从模块导入类

 来自lib.client import client 
A = client()


My (simplified) project layout is as follows:

/__init__.py
/test.py
/lib/__init__.py
/lib/client.py

my test.py is simply:

import lib.client
A = client()
A.Test()

and my lib\client.py begins as follows:

import ui #(another class in the lib dir)

class client(object):
    """
    (Blah)
    """
    UI = None

    def __init__():
        UI = ui()

    def Test():
        print "Success"

When I attempt to run test.py, I can step into the code and see that the definitions in client are parsed, however, when I get to the line where I instantiate a client, I get the following exception:

NameError: name 'client' is not defined

if I change that line to be:

A = lib.client()

Then I get

'module' object is not callable

What am I missing?

解决方案

the lib.client object you have after import lib.client is the module, not the class. To instantiate the class you need to call the class in the module object:

A = lib.client.client()

or, as @rantanplan said, import the class from the module

from lib.client import client
A = client()

这篇关于无法实例化在子目录中定义的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆