This seems like a silly question but I haven't been able to come across the answer anywhere. Within my various packages I have a set of modules, usually each containing one class. When I want to create an instance of a class I have to refer to it twice:
Example: package/obj.py:
class obj(object):
pass
file.py:
import package.obj
my_obj = package.obj.obj()
Is there a way to reorganize my code such that I don't have to type the name twice? Ideally I'd like to just have to type package.obj().
Python is not Java. Feel free to put many classes into one file and then name the file according to the category:
import mypackage.image
this_image = image.png(...)
that_image = image.jpeg(....)
If your classes are so large you want them in separate files to ease the maintenance burden, that's fine, but you should not then inflict extra pain on your users (or yourself, if you use your own package ;). Gather your public classes in the package's __init__
file (or a category file, such as image
) to present a fairly flat namespace:
mypackage's __init__.py
(or image.py
):
from _jpeg import jpeg
from _png import png
mypackage's _jpeg.py
:
class jpeg(...):
...
mypackage's _png.py
:
class png(...):
...
user code:
# if gathered in __init__
import mypackage
this_image = mypackage.png(...)
that_image = mypackage.jpeg(...)
or:
# if gathered in image.py
from mypackage import image
this_image = image.png(...)
that_image = image.jpeg(....)
You can use from ... import ...
statement:
from package.obj import obj
my_obj = obj()
Give your classes and modules meaningful names. That's the way. Name your module 'classes' and name your class 'MyClass'.
from package.classes import MyClass
myobj = MyClass()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With