python class variable not visible in __init__?

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

    I get the following error:

    Traceback (most recent call last):
      Line 1, in 
        class Foo(object):
      Line 3, in Foo
        def __init__(self, custom=Foo.custom):
    NameError: name 'Foo' is not defined
    

    This is because the name Foo is in the process of being defined as the __init__ function is defined, and is not fully available at that time.

    The solution is to avoid using the name Foo in the function definition (I also renamed the custom paramter to acustom to distinguish it from Foo.custom):

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

提交回复
热议问题