天天看點

Python3 - Basics 4 「Functions + Classes & Objects + Dictionaries」

1.Functions 

-We use keyword 'def' to define our functions.

-Our functions can receive arguments from the caller.

-Our functions can return a value to the caller.

Just as follows

//Function without arguments and return 
def myFunction1():
    print("Hello World")

//Function with arguments
def myFunction2(username, greeting):
    print("Hello, %s ,From My Function!, I wish you %s" % (username, greeting)

//Function with arguments and return 
def myFunction3(a, b):
    return a + b
           
-And how do we call functions in Python ? (In this place, we just use the definitions above)
myFunction1()

myFunction2("Sharon","all the best")

myFunction3(1,2)
           

2.Classes and Objects

-Objects are an encapsulation of variables and functions into a single entity.

-Objects get their variables and functions from classes.

-Classes are essentially a template to create your objects.

-A basic class would look like this 

class Myclass:
    variable = "blalalala"
    
    def function(self):
        print("This is a message inside the class")
           
-And to assign the class above
myObject1 = Myclass()
           
-To access the variable / function inside of the newly created object.
myObject1.variable
or
print(myObject1.variable)


myObject2.function()
           
-As we already know that the variable in the class has been defined as "blalala" , we can actually change the variables of the object if you create a new object. Pleace pay attention that the variable we change is the variable which belongs to the object , not the class. We can do the change as follows.
myObject2 = Myclass()
myObject2.variable = "newly changed one "
           

3.Dictionaries

-A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key , which is any type of object (a string, a numner, a list , etc.) instead of using its index to address it.

-Pleace pay attention that we use { } to define dictionaries as follows.

phonebook = {"John":1111,"Sharon":2222}

print(phonebook)

//{'John':1111,'Sharon':2222}
           
-And we can add the key and value as follows.
phonebook["Aaron"] = 3333

print(phonebook)

//{'John':1111,'Sharon':2222,'Aaron':3333}
           

-To interate over dictionaries.

-Does not keep the order of the values stored in it.

-To iterate over key value pairs, use the following syntax:

for name, number in phonebook.items():
    print("Phone number of %s is %d" % (name, number))
           
-How to remove a pair of key and value ?
del phonebook["John"]
print(phonebook)
or
phonebook.pop("John")
print(phonebook)
           
-To know if "John" is in the dictionary ? Use "if" 
if "John" in phonebook:
    print("John is listed in the phonebook")

if "John" not in phonebook:
    print("John is not listed in the phonebook")