Unable to instantiate a class defined in a subdire

2019-02-19 10:40发布

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?

2条回答
祖国的老花朵
2楼-- · 2019-02-19 11:21

I just understood that you do the imports the Java way.

In python when you do :

import lib.client

You don't make available all the definitions in that module. You just made available the actual module - the client.py

So either you keep the import scheme as you have now and do

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

or

from lib.client import client
A = client()

Also I suggest you name your python classes with capitalized camelcase i.e.

class Client(object):

As it is the python convention.

查看更多
Summer. ? 凉城
3楼-- · 2019-02-19 11:41

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()
查看更多
登录 后发表回答