python class variable not visible in __init__?

前端 未结 4 1251
孤街浪徒
孤街浪徒 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:35

    What we do instead is the following

    class Foo( object ):
        custom = 1
        def __init__( self, arg=None )
            self._custom = self.custom if arg is None else arg
    

    This bypasses the confusing issue of whether or not the name Foo has been defined yet.

提交回复
热议问题