34

I am learning python and doing an exercise about classes. It tells me to add an 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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Brandon Kheang
  • 597
  • 1
  • 6
  • 19
  • 1
    For a class `Foo`, you call an attribute (a class variable) as `Foo().bar`. You call a method (a class function) as `Foo().baz()`. – pylang Sep 20 '17 at 03:13
  • Possible duplicate of [Difference between calling a method and accessing an attribute](https://stackoverflow.com/questions/17000450/difference-between-calling-a-method-and-accessing-an-attribute) – Shreshth Kharbanda Nov 12 '17 at 21:16
  • 1
    @pylang Without forgetting the static method `Foo.wololo`. – Guimoute Aug 25 '20 at 13:48

6 Answers6

51

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 attribute
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • Minor fix: `d = C()` and `d.e = 30` should be un-indented. – Jeremy McGibbon Sep 20 '17 at 03:11
  • 2
    Did you just create and set an attribute by doing `e.g = 40` outside of the class definition? I see no attribute of class C, defined in the class definition. Is this typical/recommended? – Semihcan Doken Oct 05 '17 at 21:48
  • 1
    I think the really interesting distinction to clarify would be a method vs an attribute that happens to be a function. – max Oct 05 '18 at 05:45
17

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.

Jeremy McGibbon
  • 3,527
  • 14
  • 22
  • 1
    Nitpick: *methods belong to the class*. – juanpa.arrivillaga Sep 20 '17 at 02:56
  • I'd rather not get into the weeds on something like that. For example, `[].sort is [].sort` evaluates to `False` because there is a method object for each instance. – Jeremy McGibbon Sep 20 '17 at 03:05
  • ... generally. At least, `my_method` does. You can dynamically add methods to an instance, though. – juanpa.arrivillaga Sep 20 '17 at 03:05
  • 3
    Sure, I did say nitpick :). But, then again, `x = []; x.sort is x.sort` *also evaluates to `False`.* Because, again, the method doesn't *belong* to the instance. It is dynamically bound to the instance *on each method call*. Rather, a new method-object is created each time you call a method! There is a method object **for each time you access a method** using `my_instance.my_method`. So, of course, `s = x.sort; s is s` evaluates to `True` – juanpa.arrivillaga Sep 20 '17 at 03:09
  • 1
    Good explanation. We can verify the following using the in-built function `getattr()`. Therefore methods are indeed attributes of a class (class attributes), consequently, these methods are instance attributes as well. – Nameless Apr 01 '21 at 20:57
15

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()
Dharman
  • 30,962
  • 25
  • 85
  • 135
JamesAng
  • 344
  • 2
  • 9
1

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.

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80
  • For Python 3, you don't need to inherit from `object`, and you need parentheses in the `print` call. Combining two strings just to `print` the combination and then discard it is vaguely unpythonic to me; probably use string formatting instead (though I don't think there is any performance difference). – tripleee Jul 07 '19 at 08:57
  • Agreed. I just needed a simple example for the original question. – Chris Johnson Jul 07 '19 at 13:33
0
class example:
    global a
    # a=0

    def __init__(self,x,y):
        self.fname=x
        self.lname=y
    def show(self):
        return "first name: {} & Last name: {}".format(self.fname,self.lname)

obj1=example('reyan','ishtiaq')
obj2=example('ishtiaq','reyan')

print('method associated with obj1: '+ obj1.show())
print('method associated with obj2: '+ obj2.show())

obj1.a=20
obj2.a=30

print(obj1.a)
print(obj2.a)

output: method associated with obj1: first name: reyan & Last name: ishtiaq................ method associated with obj2: first name: ishtiaq & Last name: reyan................ 20 30

-1

#Below u can see that I made a class called "example" with two class attributes: variable1 and variable2.

class example(): def init(self, variable1, variable2): self.variable1 = variable1 self.variable2 = variable1

i did not construct a method inside this class. Notice that variable1 comes first and after comes variable2 inside the init():

#below i created an object "object1" with the example class. I created the example class with two arguments "variable1" and "variable2". "self" does not count), so i have to pass two arguments when calling the example class. I gave two variables "10" and "20".

object1 = example(10,20)

with the code below i just get the value of the first argument, which is 10.

print(object1.variable1)

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 21 '23 at 06:42