Python object initialization bug. Or am I misunderstanding how objects work?

后端 未结 5 866
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 15:29
  1 import sys
  2 
  3 class dummy(object):
  4     def __init__(self, val):
  5         self.val = val
  6 
  7 class myobj(object):
  8     def __init__(self, resourc         


        
5条回答
  •  太阳男子
    2021-01-23 16:06

    Please read this answer for a discussion of how to setup a class from __init__(). You have encountered a well-known quirk of Python: you are trying to set up a mutable, and your mutable is being evaluated once when __init__() is compiled. The standard workaround is:

    class ext(myobj):
        def __init__(self, resources=None):
            if resources is None:
                resources = []
            #myobj.__init__(self, resources)
            self._resources = resources
    

提交回复
热议问题