Python/Simple Package: Difference between revisions
From charlesreid1
(Created page with "==Redefining an Object== Scenario: you are defining an object, and want to extend it by adding additional methods. ===How not to do it=== The following method will not work...") |
|||
| Line 18: | Line 18: | ||
4 files | 4 files | ||
$ cat pkg_test/__init__.py | |||
from .a import * | |||
from .b import * | |||
from .c import * | |||
Revision as of 02:00, 11 September 2018
Redefining an Object
Scenario: you are defining an object, and want to extend it by adding additional methods.
How not to do it
The following method will not work - each time you redefine the object in a subsequent file, all definitions in prior files are lost.
A very simple python package:
$ 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(object):
def bar(self):
print('bar')
$ cat pkg_test/c.py
from .a import EchoBase
class EchoBase(object):
def buz(self):
print('buz')
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() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'EchoBase' object has no attribute 'foo' >>> e.bar() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'EchoBase' object has no attribute 'bar' >>> e.buz() buz
Only the method defined in c.py, the last file imported, is defined in the end.