Difference between methods and attributes in python

后端 未结 5 412
渐次进展
渐次进展 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:52

    A quick,simplified explanation.

    Attribute == characteristics. Method == operations/ actions.

    For example, Let's describe a cat (meow!).

    What are the attributes(characteristics) of a cat? It has different breed, name, color, whether they have spots...etc.

    What are methods (actions) of a cat? It can meow, climb, scratch you, destroy your laptop, etc.

    Notice the difference, attributes define characteristics of the cat.

    Methods, on the other hand, defines action/operation (verb).

    Now, putting the above definition in mind, let's create an object of class 'cat'...meowww

    class Cat():
    

    To create attributes, use def init(self, arg1, arg2) - (as shown below).

    The 'self' keyword is a reference to a particular instance of a class.

    def __init__(self, mybreed, name):
        
        # Attributes
        self.breed = mybreed
        self.name = name
    
    # Operations/actions --> methods
    def kill_mouse(self):
        print('Insert some method to kill mouse here')
    

    Notice (above) 'mybreed' is an input argument that the user need to specify, whereas self.breed is an attribute of the instance assigned to 'mybreed' argument. Usually, they're the same (e.g. breed for both, self.breed = breed). Here, it's coded differently to avoid confusion.

    And attributes are usually written as 'self.attribute_name' (as shown above).

    Now, methods are more like actions, or operations, where you define a function inside the body of a class to perform some operation, for example, killing a mouse. A method could also utilize the attributes that you defined within the object itself.

    Another key difference between a method and attribute is how you call it.

    For example, let's say we create an instance using the above class we defined.

    my_cat = Cat()
    

    To call an attribute, you use

    my_cat.name
    

    or

    my_cat.breed
    

    For methods, you call it to execute some action. In Python, you call method with an open and close parenthesis, as shown below:

    my_cat.kill_mouse()
    

提交回复
热议问题