Difference between methods and attributes in python

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

    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.

提交回复
热议问题