Search code examples
pythonclassoopmethodsattributes

Difference between methods and attributes in python


I am learning python and doing an exercise about classes. It tells me to add an attribute to my class and a method to my class. I always thought these were the same thing until I read the exercise. What is the difference between the two?


Solution

  • 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 attribute