每一种编程语言都离不开函数,Python也不例外,关于Python函数的定义: 以def关键词开头,后接函数名和圆括号(); 函数执行的代码以:起始,并且缩进; return[表达式]结束函数,选择性的返回一个值给调用方。不带表达式的return相当于返回None。
例:
def printme(str): print(str) printme("我要调用用户自定义函数!") # 我要调用用户自定义函数! printme("再次调用同一函数") # 再次调用同一函数 temp = printme('hello') # hello print(temp) # NonePython的参数从简到繁的形态:
位置参数(positional argument)默认参数(default argument)可变参数(variable argument)关键字参数(keyword argument)命名关键字参数(name keyword argument)参数组合 调用参数时,如果没有值的传入,则被认为是使用默认值。 默认参数一定要放在位置参数后面,否则会报错。 例: def printinfo(name, age=8): print('Name:{0},Age:{1}'.format(name, age)) printinfo('小马') # Name:小马,Age:8 printinfo('小马', 10) # Name:小马,Age:10defprintfo在大部分编程语言中函数调用时参数的顺序与声明必须一致,但是在Python中可以不一致,因为Python解释器能够用参数名匹配参数值。 例:
def printinfo(name, age): print('Name:{0},Age:{1}'.format(name, age)) printinfo(age=8, name='小马') # Name:小马,Age:8定义在函数内部的变量拥有局部作用域,该变量称为局部变量。 定义在函数外部的变量拥有全局作用域,该变量称为全局变量。
def discounts(price, rate): final_price = price * rate return final_price old_price = float(input('请输入原价:')) # 98 rate = float(input('请输入折扣率:')) # 0.9 new_price = discounts(old_price, rate) print('打折后价格是:%.2f' % new_price) # 88.20但是,当内部作用域想要修改外部作用域的变量是,就要用到两个关键字:global、nonlocal。
num = 1 def fun1(): global num # 需要使用 global 关键字声明 print(num) # 1 num = 123 print(num) # 123 fun1() print(num) # 123Python中的两类函数:
第一类:用def关键字定义的正规函数第二类用lambda关键字定义的匿名函数 在函数参数和表达式中间要加个冒号。 例: def sqr(x): return x ** 2 print(sqr) # <function sqr at 0x000000BABD3A4400> y = [sqr(x) for x in range(10)] print(y) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] lbd_sqr = lambda x: x ** 2 print(lbd_sqr) # <function <lambda> at 0x000000BABB6AC1E0> y = [lbd_sqr(x) for x in range(10)] print(y) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] sumary = lambda arg1, arg2: arg1 + arg2 print(sumary(10, 20)) # 30 func = lambda *args: sum(args) print(func(1, 2, 3, 4, 5)) # 15定义Python类可以使用关键字class,关键字后面要紧跟类的名称、分号和类的实现。
class Turtle: # Python中的类名约定以大写字母开头 """关于类的一个简单例子""" # 属性 color = 'green' weight = 10 legs = 4 shell = True mouth = '大嘴' # 方法 def climb(self): print('我正在很努力的向前爬...') def run(self): print('我正在飞快的向前跑...') def bite(self): print('咬死你咬死你!!') def eat(self): print('有得吃,真满足...') def sleep(self): print('困了,睡了,晚安,zzz') tt = Turtle() print(tt) # <__main__.Turtle object at 0x0000007C32D67F98> print(type(tt)) # <class '__main__.Turtle'> print(tt.__class__) # <class '__main__.Turtle'> print(tt.__class__.__name__) # Turtle tt.climb() # 我正在很努力的向前爬... tt.run() # 我正在飞快的向前跑... tt.bite() # 咬死你咬死你!! # Python类也是对象。它们是type的实例 print(type(Turtle)) # <class 'type'>继承:子类自动共享父类之间数据和方法的机制
class MyList(list): pass lst = MyList([1, 5, 2, 7, 8]) lst.append(9) lst.sort() print(lst) # [1, 2, 5, 7, 8, 9]多态:不同对象对同一方法响应不同的行动
class Animal: def run(self): raise AttributeError('子类必须实现这个方法') class People(Animal): def run(self): print('人正在走') class Pig(Animal): def run(self): print('pig is walking') class Dog(Animal): def run(self): print('dog is running') def func(animal): animal.run() func(Pig()) # pig is walkingPython中的self相当于c++的this指针 例:
class Test: def prt(self): print(self) print(self.__class__) t = Test() t.prt() # <__main__.Test object at 0x000000BC5A351208> # <class '__main__.Test'>Python有一个魔法方法,该方法在类实例化时会自动调用。 例:
class Ball: def __init__(self, name): self.name = name def kick(self): print("我叫%s,该死的,谁踢我..." % self.name) a = Ball("球A") b = Ball("球B") c = Ball("球C") a.kick() # 我叫球A,该死的,谁踢我... b.kick() # 我叫球B,该死的,谁踢我...在变量或函数名前加上"_"两个下划线,那么这个函数或变量就会为私有的了。 例:
class JustCounter: __secretCount = 0 # 私有变量 publicCount = 0 # 公开变量 def count(self): self.__secretCount += 1 self.publicCount += 1 print(self.__secretCount) counter = JustCounter() counter.count() # 1 counter.count() # 2 print(counter.publicCount) # 2 # Python的私有为伪私有 print(counter._JustCounter__secretCount) # 2 print(counter.__secretCount) # AttributeError: 'JustCounter' object has no attribute '__secretCount'例:
class Turtle: def __init__(self, x): self.num = x class Fish: def __init__(self, x): self.num = x class Pool: def __init__(self, x, y): self.turtle = Turtle(x) self.fish = Fish(y) def print_num(self): print("水池里面有乌龟%s只,小鱼%s条" % (self.turtle.num, self.fish.num)) p = Pool(2, 3) p.print_num() # 水池里面有乌龟2只,小鱼3条魔法方法总是被下划线包围,例:__init__
例:
class Rectangle: def __init__(self, x, y): self.x = x self.y = y def getPeri(self): return (self.x + self.y) * 2 def getArea(self): return self.x * self.y rect = Rectangle(4, 5) print(rect.getPeri()) # 18 print(rect.getArea()) # 20例:
class C: pass print(type(len)) # <class 'builtin_function_or_method'> print(type(dir)) # <class 'builtin_function_or_method'> print(type(int)) # <class 'type'> print(type(list)) # <class 'type'> print(type(tuple)) # <class 'type'> print(type(C)) # <class 'type'> print(int('123')) # 123 # 这个例子中list工厂函数把一个元祖对象加工成了一个列表对象。 print(list((1, 2, 3))) # [1, 2, 3]Python中的协议像是一种指南。 例:
class CountList: def __init__(self, *args): self.values = [x for x in args] self.count = {}.fromkeys(range(len(self.values)), 0) def __len__(self): return len(self.values) def __getitem__(self, item): self.count[item] += 1 return self.values[item] c1 = CountList(1, 3, 5, 7, 9) c2 = CountList(2, 4, 6, 8, 10) print(c1[1]) # 3 print(c2[2]) # 6 print(c1[1] + c2[1]) # 7 print(c1.count) # {0: 0, 1: 2, 2: 0, 3: 0, 4: 0} print(c2.count) # {0: 0, 1: 1, 2: 1, 3: 0, 4: 0}