Python/Simple Package
From charlesreid1
Redefining an Object
Scenario: you are defining an object, and want to extend it by adding additional methods.
The trick: in the first file, we define a class called EchoBase
with the following line:
class EchoBase(object):
and in subsequent classes, we extend this definition without overwriting it by re-defining EchoBase
as follows:
class EchoBase(EchoBase):
Here is a very simple python package to provide an example:
$ tree pkg_test/ pkg_test/ ├── __init__.py ├── a.py ├── b.py └── c.py 4 files $ cat pkg_test/__init__.py from .a import * from .b import * from .c import * $ cat pkg_test/a.py class EchoBase(object): def __init__(self): pass def foo(self): print('foo') $ cat pkg_test/b.py from .a import EchoBase class EchoBase(EchoBase): def bar(self): print('bar') $ cat pkg_test/c.py from .b import EchoBase class EchoBase(EchoBase): def buz(self): print('buz')
IMPORTANT: Also note that c imports from b, so that their definitions are chained. If c imports from a, it overwrites changes that b makes.
Now what we can do is, from the directory where the pkg_test
directory is located, open a python prompt, and create an EchoBase
object:
$ python Python 3.6.3 |Anaconda, Inc.| (default, Oct 6 2017, 12:04:38) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import pkg_test >>> e = pkg_test.EchoBase() >>> e.foo() foo >>> e.bar() bar >>> e.buz() buz
Only the method defined in c.py
, the last file imported, is defined in the end.