Should all member variables be initialized in __init__

前端 未结 3 1150
独厮守ぢ
独厮守ぢ 2020-12-08 02:05

Maybe this is more of a style question than a technical one but I have a class with several member variables and I want to have it work so that some of the member variables

3条回答
  •  盖世英雄少女心
    2020-12-08 02:51

    Here is an excerpt from sololearn.com (a free site to learn python)

    "Properties provide a way of customizing access to instance attributes. They are created by putting the property decorator above a method, which means when the instance attribute with the same name as the method is accessed, the method will be called instead.

    One common use of a property is to make an attribute read-only."

    Example (also from sololearn.com):

    class Pizza:
        def __init__(self, toppings):
        self.toppings = toppings
    
        @property
        def pineapple_allowed(self):
           return False
    
       pizza = Pizza(["cheese", "tomato"])
       print(pizza.pineapple_allowed)
       pizza.pineapple_allowed = True
    

    Result:

      >>>
     False
     AttributeError: can't set attribute
     >>>
    

    If var3 depends on var1 and var2 you could do

    class myClass:
        def __init__(self,var1,var2):
            self.var1=var1
            self.var2=var2
        @property
        def var3(self):
            return(self.var1+self.var2)  #var3 depends on var1 and var2
     m1=myClass(1,2)
     print(m1.var3)   # var3 is 3
    

    var3 can also be set to whatever you want using a setter function. Note that you can avoid setting var3 to an arbitrary value by using None.

    class myClass2(object):
        def __init__(self,var1,var2):
            self.var1=var1
            self.var2=var2
            self._var3=None     # None or an initial value that makes sense
            @property
            def var3(self):
                return(self._var3)
            @var3.setter
            def var3(self,value):
                self._var3=value
       m2=myClass(1,2)
       print(m2.var3)        # var3 is none
       print(m2.var3(10))    # var3 is set to 10 
    

提交回复
热议问题