Use a class in the context of a different module

后端 未结 7 1509
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 08:53

I want to modify some classes in the standard library to use a different set of globals the ones that other classes in that module use.

Example

This exampl

相关标签:
7条回答
  • 2021-01-12 09:51

    Globals are rarely a good idea.

    Implicit variables are rarely a good idea.

    An implicitly-used global is easy to indict as also "rarely good".

    Additionally, you don't want A.__init__() doing anything "class-level" like updating some mysterious collection that exists for the class as a whole. That's often a bad idea.

    Rather than mess with implicit class-level collection, you want a Factory in module_a that (1) creates A or B instances and (b) updates an explicit collection.

    You can then use this factory in module_b, except with a different collection.

    This can promote testability by exposing an implicit dependency.

    module_a.py

    class Factory( object ):
        def __init__( self, collection ):
            self.collection= collection
        def make( self, name, *args, **kw ):
            obj= eval( name )( *args, **kw )
            self.collection.append( obj )
            return obj
    
    module_collection = []
    factory= Factory( module_collection )
    

    module_b.py

    module_collection = []
    factory = module_a.Factory( module_collection )
    

    Now a client can do this

    import module_b
    a = module_b.factory.make( "A" )
    b = module_b.factory.make( "B" )
    print( module_b.module_collection )
    

    You can make the API a bit more fluent by making the factory "callable" (implementing __call__ instead of make.

    The point is to make the collection explicit via a factory class.

    0 讨论(0)
提交回复
热议问题