Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 until I read the exercise. What is the difference between the two?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
809 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...