Difference between methods and attributes in python

后端 未结 5 430
渐次进展
渐次进展 2020-12-15 13:09

I am learning python and doing an exercise about classes. It tells me to add nd attribute to my class and a method to my class. I always thought these were the same thing un

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 13:42

    Terminology

    Mental model:

    • A variable stored in an instance or class is called an attribute.
    • A function stored in an instance or class is called a method.

    According to Python's glossary:

    attribute: A value associated with an object which is referenced by name using dotted expressions. For example, if an object o has an attribute a it would be referenced as o.a

    method: A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). See function and nested scope.

    Examples

    Terminology applied to actual code:

    a = 10                          # variable
    
    def f(b):                       # function  
        return b ** 2
    
    class C:
    
        c = 20                      # class attribute
    
        def __init__(self, d):      # "dunder" method
            self.d = d              # instance attribute
    
        def show(self):             # method
            print(self.c, self.d) 
    
    e = C(30)
    e.g = 40                        # another instance variable
    

提交回复
热议问题