简体   繁体   中英

Distutils - Where Am I going wrong?

I wanted to learn how to create python packages, so I visited http://docs.python.org/distutils/index.html .

For this exercise I'm using Python 2.6.2 on Windows XP.

I followed along with the simple example and created a small test project:

person/

    setup.py

    person/
       __init__.py
       person.py

My person.py file is simple:

class Person(object):   
    def __init__(self, name="", age=0):
        self.name = name
        self.age = age

    def sound_off(self):
        print "%s %d" % (self.name, self.age)

And my setup.py file is:

from distutils.core import setup
setup(name='person',
    version='0.1',
    packages=['person'],
    )

I ran python setup.py sdist and it created MANIFEST, dist/ and build/. Next I ran python setup.py install and it installed it to my site packages directory.

I run the python console and can import the person module, but I cannot import the Person class.

>>>import person
>>>from person import Person
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name Person

I checked the files added to site-packages and checked the sys.path in the console, they seem ok. Why can't I import the Person class. Where did I go wrong?

person/
   __init__.py
   person.py

You've got a package called person , and a module inside it called person.person . You defined the class in that module, so to access it you'd have to say:

import person.person
p= person.person.Person('Tim', 42)

If you want to put members directly inside the package person , you'd put them in the __init__.py file.

Your question isn't really about distutils packages, but about Python packages -- a related but different thing with the same name. Packages in Python are a separate kind of module, that are directories with an __init__.py file. You created a person package with a person module with a Person class. import person gives you the package. If you want the person module inside the person package, you need import person.person . And if you want the Person class inside the person module inside the person package, you need from person.person import Person .

These things get a lot more obvious when you don't give different things the same name, and also when you don't put classes in separate modules for their own sake. Also see Should I create each class in its own .py file?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM