In [2]:
def hello(a,b):
return a+b
In [3]:
hello(1,1)
Out[3]:
In [4]:
hello('a','b')
Out[4]:
In [8]:
def Fibonacci(n):
if n < 2:
return n
else:
return Fibonacci(n-1)+Fibonacci(n-2)
print Fibonacci(10)
In [9]:
def Fibonacci(n):
return n if n < 2 else Fibonacci(n-1)+Fibonacci(n-2)
print Fibonacci(10)
Class is a blueprint defining the charactaristics and behaviors of an object.
class MyClass:
...
...
For a simple class, one shall define an instance
__init__()
to handle variable when it created. Let's try the following example:
In [30]:
class Person:
def __init__(self,age,salary):
self.age = age
self.salary = salary
def out(self):
print self.age
print self.salary
This is a basic class definition, the age
and salary
are needed when creating this object. The new class can be invoked like this:
In [33]:
a = Person(30,10000)
a.out()
The __init__
initilaze the variables stored in the class. When they are called inside the class, we should add a self.
in front of the variable. The out(Self)
method are arbitary functions that can be used by calling Yourclass.yourfunction(). The input to the functions can be added after the self input.
In [10]:
a = 'Alice'
print a
def change_my_name(my_name):
my_name = 'Bob'
change_my_name(a)
print a
In [11]:
a = 'Alice'
print a
def change_my_name(my_name):
my_name = 'Bob'
return my_name
b = change_my_name(a)
print b
In [13]:
a_list_of_names = ['Alice','Bob','Christ','Dora']
print a_list_of_names
def change_a_value(something):
something[0] = 'Not Alice'
change_a_value(a_list_of_names)
print a_list_of_names
In [14]:
a_list_of_names = ['Alice','Bob','Christ','Dora']
print a_list_of_names
a_new_list_of_names = a_list_of_names
print a_new_list_of_names
def change_a_value(something):
something[0] = 'Not Alice'
change_a_value(a_list_of_names)
print "After change_a_value:"
print a_list_of_names
print a_new_list_of_names
print "Is 'a_new_list_of_names' same as 'a_list_of_names' ?"
print a_new_list_of_names is a_list_of_names
In [15]:
some_guy = 'Alice'
a_list_of_names = []
a_list_of_names.append(some_guy)
print "Is 'some_guy' same as the first element in a_list_of_names ?"
print (some_guy is a_list_of_names[0])
In [16]:
another_list_of_names = a_list_of_names
print "Is 'a_list_of_names' same as the 'another_list_of_names' ?"
print (a_list_of_names is another_list_of_names)
In [17]:
some_guy = 'Bob'
another_list_of_names.append(some_guy)
print "We have added Bob to the list, now is 'a_list_of_names' same as the 'another_list_of_names' ? "
print (a_list_of_names is another_list_of_names)
In [18]:
print (some_guy,a_list_of_names,another_list_of_names)
some_guy = 'Christ'
print (some_guy,a_list_of_names,another_list_of_names)
In [ ]: