What is the difference between class and instance attributes?

后端 未结 5 1713
面向向阳花
面向向阳花 2020-11-21 05:44

Is there any meaningful distinction between:

class A(object):
    foo = 5   # some default value

vs.

class B(object):
    d         


        
5条回答
  •  天命终不由人
    2020-11-21 06:15

    Here is a very good post, and summary it as below.

    class Bar(object):
        ## No need for dot syntax
        class_var = 1
    
        def __init__(self, i_var):
            self.i_var = i_var
    
    ## Need dot syntax as we've left scope of class namespace
    Bar.class_var
    ## 1
    foo = MyClass(2)
    
    ## Finds i_var in foo's instance namespace
    foo.i_var
    ## 2
    
    ## Doesn't find class_var in instance namespace…
    ## So look's in class namespace (Bar.__dict__)
    foo.class_var
    ## 1
    

    And in visual form

    Class attribute assignment

    • If a class attribute is set by accessing the class, it will override the value for all instances

      foo = Bar(2)
      foo.class_var
      ## 1
      Bar.class_var = 2
      foo.class_var
      ## 2
      
    • If a class variable is set by accessing an instance, it will override the value only for that instance. This essentially overrides the class variable and turns it into an instance variable available, intuitively, only for that instance.

      foo = Bar(2)
      foo.class_var
      ## 1
      foo.class_var = 2
      foo.class_var
      ## 2
      Bar.class_var
      ## 1
      

    When would you use class attribute?

    • Storing constants. As class attributes can be accessed as attributes of the class itself, it’s often nice to use them for storing Class-wide, Class-specific constants

      class Circle(object):
           pi = 3.14159
      
           def __init__(self, radius):
                self.radius = radius   
          def area(self):
               return Circle.pi * self.radius * self.radius
      
      Circle.pi
      ## 3.14159
      c = Circle(10)
      c.pi
      ## 3.14159
      c.area()
      ## 314.159
      
    • Defining default values. As a trivial example, we might create a bounded list (i.e., a list that can only hold a certain number of elements or fewer) and choose to have a default cap of 10 items

      class MyClass(object):
          limit = 10
      
          def __init__(self):
              self.data = []
          def item(self, i):
              return self.data[i]
      
          def add(self, e):
              if len(self.data) >= self.limit:
                  raise Exception("Too many elements")
              self.data.append(e)
      
       MyClass.limit
       ## 10
      

提交回复
热议问题