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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Terminology
Mental model:
According to Python's glossary:
Examples
Terminology applied to actual code:
A method is an attribute, but not all attributes are methods. For example, if we have the class
This class has two attributes,
class_name
andmy_method
. But onlymy_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.A method is a function defined in the class. An attribute is an instance variable defined in the class.
Example:
Here
hello
is a method, andname
is an attribute.