Difference between methods and attributes in pytho

2020-03-21 05:41发布

问题:

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?

回答1:

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


回答2:

A method is an attribute, but not all attributes are methods. For example, if we have the class

class MyClass(object):

    class_name = 'My Class'

    def my_method(self):
        print('Hello World!')

This class has two attributes, class_name and my_method. But only my_method is a method. Methods are functions that belong to your object. There are additional hidden attributes present on all classes, but this is what your exercise is likely talking about.



回答3:

A method is a function defined in the class. An attribute is an instance variable defined in the class.

Example:

class Example(object):
    def __init__(self, name):
        self.name = name
    def hello(self):
        print 'Hi, I am ' + self.name

Here hello is a method, and name is an attribute.