Add Functions (Methods) to Class

Other than data attributes, a class can also have function attributes. Functions defined in a class by default operate on instances, in other words, they 'belong to' an object of the class.

Functions belong to an object are also called methods.

They always takes at least one argument (also the first argument), self, which refers to the object itself that the functions 'belong to'.

Sounds confusing? You will understand the new concepts slowly.

Let's use an example to help explain. Now, on top of the above example Apple class, I will add a function say() in it:

class Apple:
    name = "Golden Delicious"           

    def say(self):
        print("An apple a day keeps the doctor away!")

# create a new instance/object
a2 = Apple()          # a2 is an object of Apple class

# access the attributes of the object
print( a2.name)       # Golden Delicious
a2.say()              # An apple a day keeps the doctor away!

a2 is Apple object, it's a instance of Apple class, it has the attributes: a variable name and a method say() defined in the class. We access them using a2.name and a2.say()

A little about self

Class methods have only one specific difference from ordinary functions - they must have self as the first parameter in the parameter list, this particular variable refers to the object itself. The use of self is a universal convention in Python. (some other languages, such as Java and C++, require to use the word this).

Call the method

When you call the method you do not give a value for self parameter, Python will provide it.

If the method has no other input arguments, then it's defined with only self parameter, like say(self) in Apple class. When it's called, the self is omitted so the parenthesis is empty as a2.say()

We will talk more about self later.

Method with more input parameters other than self

When the method has more input parameters other than self, you need to provide matching values for them when you call it.

For example, let's add another method to Apple class, tellColor(self, color), other than self it has one more input parameter color:

class Apple:           
    name = "Golden Delicious"

    def say(self):
        print("An apple a day keeps the doctor away!")

    def tellColor(self, color):
        print("The color is " + color)

# create an object of the class:        
a3 = Apple()
print(a3.name)             # Golden Delicious
a3.say()                   # An apple a day keeps the doctor away!

a3.tellColor("yellow")     # The color is yellow

When we call the object method, a3.tellColor("yellow"), in the parenthesis we provide value "yellow" for the parameter color. Then this method prints out a message using this value: The color is yellow

results matching ""

    No results matching ""