Python and reference passing. Limitation?

后端 未结 4 1119
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 09:17

I would like to do something like the following:

class Foo(object):
    def __init__(self):
        self.member = 10
        pass

def factory(foo):
    foo          


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-18 10:10

    The Assignment Statements section of the Python docs might be interesting.

    The = statement in Python acts differently depending on the situation, but in the case you present, it just binds the new object to a new local variable:

    def factory(foo):
        # This makes a new instance of Foo,
        # and binds it to a local variable `foo`,
        foo = Foo()
    
    # This binds `None` to a top-level variable `aTestFoo`
    aTestFoo = None
    
    # Call `factory` with first argument of `None`
    factory(aTestFoo)
    
    print aTestFoo.member
    

    Although it can potentially be more confusing than helpful, the dis module can show you the byte-code representation of a function, which can reveal how Python works internally. Here is the disassembly of `factory:

    >>> dis.dis(factory)
      4           0 LOAD_GLOBAL              0 (Foo)
                  3 CALL_FUNCTION            0
                  6 STORE_FAST               0 (foo)
                  9 LOAD_CONST               0 (None)
                 12 RETURN_VALUE        
    

    What that says is, Python loads the global Foo class by name (0), and calls it (3, instantiation and calling are very similar), then stores the result in a local variable (6, see STORE_FAST). Then it loads the default return value None (9) and returns it (12)

    What is the pythonic way of performing that ? Is it a pattern to avoid ? If it is a current mistake, how is it called ?

    Factory functions are rarely necessary in Python. In the occasional case where they are necessary, you would just return the new instance from your factory (instead of trying to assign it to a passed-in variable):

    class Foo(object):
        def __init__(self):
            self.member = 10
            pass
    
    def factory():
        return Foo()
    
    aTestFoo = factory()
    
    print aTestFoo.member
    

提交回复
热议问题