1. 程式人生 > 實用技巧 >三小時快速入門Python第四篇--函式與物件

三小時快速入門Python第四篇--函式與物件

函式與物件

1、函式

 1 # 使用 "def" 來建立一個新的函式
 2 def add(x, y):
 3     print ("x is {0} and y is {1}".format(x, y))
 4     return x + y    # 用 return 語句返回值
 5 # 呼叫函式
 6 add(5,6) #=>prints out "x is 5 and y is 6" 返回值為11
 7 # 使用關鍵字引數呼叫函式
 8 add(y=6, x=5)   # 關鍵字引數可以不在乎引數的順序
 9 # 函式的引數個數可以不定,使用*號會將引數當作元組
10 def
varargs(*args): 11 return args 12 varargs(1, 2, 3) # => (1, 2, 3) 13 14 # 也可以使用**號將引數當作字典型別 15 def keyword_args(**kwargs): 16 return kwargs 17 # 呼叫一下試試看 18 keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} 19 20 # 兩種型別的引數可以同時使用 21 def all_the_args(*args, **kwargs):
22 print (args) 23 print (kwargs) 24 """ 25 all_the_args(1, 2, a=3, b=4) prints: 26 (1, 2) 27 {"a": 3, "b": 4} 28 """ 29 30 # When calling functions, you can do the opposite of args/kwargs! 31 # Use * to expand positional args and use ** to expand keyword args. 32 args = (1, 2, 3, 4)
33 kwargs = {"a": 3, "b": 4} 34 all_the_args(*args) # 相當於 foo(1, 2, 3, 4) 35 all_the_args(**kwargs) # 相當於 foo(a=3, b=4) 36 all_the_args(*args, **kwargs) # 相當於 foo(1, 2, 3, 4, a=3, b=4) 37 # you can pass args and kwargs along to other functions that take args/kwargs 38 # by expanding them with * and ** respectively 39 def pass_all_the_args(*args, **kwargs): 40 all_the_args(*args, **kwargs) 41 print (varargs(*args)) 42 print (keyword_args(**kwargs)) 43 44 # Returning multiple values (with tuple assignments) 45 # 多個返回值 46 def swap(x, y): 47 return y, x # Return multiple values as a tuple without the parenthesis. 48 # (Note: parenthesis have been excluded but can be included) 49 50 x = 1 51 y = 2 52 x, y = swap(x, y) # => x = 2, y = 1 53 # (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.

2、函式作用域

 1 x=5
 2 def set_x(num):
 3     # 區域性變數x與全域性變數x不相同
 4     x = num # => 43
 5     print(x) # => 43
 6 def set_global_x(num):
 7     global x
 8     print(x) # => 5
 9     x = num # 全域性變數被設定成為6
10     print(x) # => 6
11 set_x(43)
12 set_global_x(6)
13 
14 # 函式也可以是物件
15 def create_adder(x):
16     def adder(y):
17         return x + y
18     return adder
19 add_10 = create_adder(10)
20 add_10(3)   # => 13
21 # 匿名函式
22 (lambda x: x > 2)(3)   # => True
23 (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
24 # 高階函式
25 map(add_10, [1, 2, 3])   # => [11, 12, 13]
26 map(max, [1, 2, 3], [4, 2, 1])   # => [4, 2, 3]
27 filter(lambda x: x > 5, [3, 4, 5, 6, 7])   # => [6, 7]
28 # We can use list comprehensions for nice maps and filters
29 [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
30 [x for x in[3,4,5,6,7] if x>5] #=>[6,7]

3、面向物件

# 繼承 object 建立一個子類
class Human(object):
    # 一個類屬性,所有該類的例項都可以訪問
    species = "H. sapiens"
    # 基礎例項化方法,在建立一個例項時呼叫
    # 注意在名稱前後加雙下劃線表示物件或者屬性是 Python 的特殊用法,但使用者可以自己控制
    # 最好不要在自己的方法前這樣使用
    def __init__(self, name):
        # 將引數賦值給例項屬性
        self.name = name
        # 初始化屬性
        self.age = 0
    # 一個例項方法。所有例項方法的第一個屬性都是self
    def say(self, msg):
        return "{0}: {1}".format(self.name, msg)

    # A class method is shared among all instances
    # They are called with the calling class as the first argument
    @classmethod
    def get_species(cls):
        return cls.species

    # A static method is called without a class or instance reference
    @staticmethod
    def grunt():
        return "*grunt*"

    # A property is just like a getter.
    # It turns the method age() into an read-only attribute
    # of the same name.
    @property
    def age(self):
        return self._age

    # This allows the property to be set
    @age.setter
    def age(self, age):
        self._age = age

    # This allows the property to be deleted
    @age.deleter
    def age(self):
        del self._age

# 建立一個例項
i = Human(name="Ian")
print(i.say("hi")) # prints out "Ian: hi"

j = Human("Joel")
print(j.say("hello"))  # prints out "Joel: hello"

# 呼叫類方法
i.get_species()   # => "H. sapiens"

# 訪問共有變數
Human.species = "H. neanderthalensis"
i.get_species()   # => "H. neanderthalensis"
j.get_species()   # => "H. neanderthalensis"

# 呼叫靜態方法
Human.grunt()   # => "*grunt*"

# Update the property
i.age = 42

# Get the property
i.age # => 42

# Delete the property
del i.age
i.age  # => raises an AttributeError