作为Clint回答的附录,你可以使用contextlib.contextmanager简化PackageResource:
@contextlib.contextmanager
def packageResource():
class Package:
...
package = Package()
yield package
package.cleanup()
或者,尽管可能不像Pythonic那样,你可以重写Package.__new__:
class Package(object):
def __new__(cls, *args, **kwargs):
@contextlib.contextmanager
def packageResource():
# adapt arguments if superclass takes some!
package = super(Package, cls).__new__(cls)
package.__init__(*args, **kwargs)
yield package
package.cleanup()
def __init__(self, *args, **kwargs):
...
简单地使用Package(…)作为Package。
为了更简洁,请将清理函数命名为close并使用contextlib。关闭,在这种情况下,你可以使用未修改的Package类via with contextlib.closing(Package(…))或覆盖它的__new__为更简单
class Package(object):
def __new__(cls, *args, **kwargs):
package = super(Package, cls).__new__(cls)
package.__init__(*args, **kwargs)
return contextlib.closing(package)
这个构造函数是继承的,所以你可以简单地继承,例如。
class SubPackage(Package):
def close(self):
pass