Page 1 of 1

[Tutorial] Learning programming with Python, part IV

Posted: Fri Jun 01, 2012 12:50 pm
by Acid_Snake
Previously on wololo.net...
We learned how to declare variables and using them, one of values that could be assigned to the variables could be a class, but we didn't dug up more on classes so it's time we do it now.

Functions:
A function is used to create a set of codes that can be called (executed) when needed and all the times needed.
To create a function we use def followed by the name of the function:

Code: Select all

def hello():
  print "Hello World"
to call this function we simply use:

Code: Select all

hello()
We can add variables to the function that are specified when calling them:

Code: Select all

def hello(text):
  print text
so when we call it we must specify a value for text:

Code: Select all

hello(text="Hello World")
or simply:

Code: Select all

hello("Hello World")
we can call the function as many times as we want, even changing the value for text:

Code: Select all

hello("Hello World")
hello("Hola Mundo")
hello("Goodbye World")
classes and objects:
Long story short: a class is used to create an object.
An object is a class with methods (functions) and attributes:

Code: Select all

class hello:
  def hello(self, number)
    self.number = number
    print "Hello World\n" * number
We call it with:

Code: Select all

hello().hello(3)
and the result:

Code: Select all

Hello World
Hello World
Hello World
Inheritance:
To create a class and inherit from another class we use pass:

Code: Select all

class hello:
  def hello(self, number)
    self.number = number
    print "Hello World\n" * number
class world(hello):
  pass
And then:

Code: Select all

world().hello(3)
will produce the same result as before.
As you already should know, variables can also be classes:

Code: Select all

x = world()
x.hello(3)
Modules:
One thing that Python has is what they call "batteries included", that is a lot useful modules for varying uses.
To use a module one must first import it:

Code: Select all

import random
Then we can use all of that modules functions, this is an example of using the module "random" to generate a random string:

Code: Select all

random.randrange(1234567890)
More on some useful modules later.

Previous: viewtopic.php?f=37&t=11885
Next: viewtopic.php?f=37&t=11920