《Python for Beginners》为LearnStreet上的Python入门课程。
本节主要学习内容分为两部分:
1. Scoping and Mutability(变量作用域与可变性)
2. Classes and Objects(类和对象)
Lesson 8 Scoping and Mutability
1. Global and Local Variables
全局变量和局部变量
1 >>> name = "Gladys" 2 >>> other_name = "Mario the plumber" 3 >>> def run(): 4 name = "GLaDOS" 5 #write your code here 6 return name, other_name 7 8 >>> print run() 9 ('GLaDOS', 'Mario the plumber')
总结:Python中全局变量和局部变量的使用方法与C语言基本相同。
Lesson 9 Classes and Objects
1. Overview
In Python, everything we work with is an object.
self is the variable that the instance of the class is assigned to, so when initializing an instance, don't include self as a parameter.
2. Creating a class
创建一个类
1 class Bottle: 2 3 def __init__(self, liquid): 4 self.amount= 500 5 self.height = 10 6 self.empty = False 7 self.liquid = liquid 8 9 def amount_left(self): 10 print self.amount 11 12 def drink(self, amount): 13 if amount < self.amount: 14 self.amount -= amount 15 elif amount == self.amount: 16 self.amount -= amount 17 self.empty = True 18 else: 19 print "Cannot drink more " + self.liquid + " than there is!" 20 21 def refill(self, amount): 22 if amount + self.amount > 500: 23 print "Cannot add that much " + self.liquid + " to the bottle!" 24 else: 25 self.amount += amount 26 self.empty = False
总结:初始化一个类的实例时,__init__(self, arg)函数会自动执行,类似C++中的构造函数。
至此,《Python for Beginners》网络课程已经学习结束,并获得了一枚结课勋章,其图片如下所示。该课程简洁易懂,配合在线编程练习,能够及时检测学习成果,是Python入门者不错的选择。