python class variable not visible in __init__?

前端 未结 4 1242
孤街浪徒
孤街浪徒 2021-02-06 01:47

This code produces an error message, which I found surprising:

class Foo(object):
    custom = 1
    def __init__(self, custom=Foo.custom):
        self._custom          


        
4条回答
  •  北海茫月
    2021-02-06 02:22

    It's Foo that isn't visible, because you're in the middle of building it. But since you're in the same scope as custom, you can just say custom rather than Foo.custom:

    class Foo(object):
        custom = 1
        def __init__(self, mycustom=custom):
            self._custom = mycustom
    

    But note that changing Foo.custom later on won't affect the value of custom that subsequently-created Foos see:

    class Foo(object):
        custom = 1
        def __init__(self, mycustom=custom):
            self._custom = mycustom
    
    one = Foo()
    Foo.custom = 2
    two = Foo()
    print (two._custom)  # Prints 1
    

    By using a sentinel default value instead, you can get what you want:

    class Foo(object):
        custom = 1
        def __init__(self, mycustom=None):
            if mycustom is None:
                self._custom = Foo.custom
            else:
                self._custom = mycustom
    
    one = Foo()
    Foo.custom = 2
    two = Foo()
    print (two._custom)  # Prints 2
    

提交回复
热议问题