1.模块
模块和字典差不多,它的一些属性:
1.模组是包含函数和变量的Python 文件。
2.你可以import 这个文件。
3.然后你可以使用'.'操作符访问到模组中的函数和变量。
假如说有一个模块名字叫mystuff.py 并且在里边放了个叫做 apple 的函数,就像这样:
# this goes in mystuff.py
def apple():
print "I AM APPLES!"
# this is just a variable
tangerine = "Living reflection of a dream"
接下来我就可以用import 来调用这个模块,并且访问到 apple 函数和变量:
import mystuff
mystuff.apple()
print mystuff.tangerine
2.类
类和模块差不多,通过类,可以把一组函数和数据放到一个容器中,从而用'.'操作符访问到它们使用创建 mystuff 模块的方法来创建一个类:
class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print "I AM CLASSY APPLES!"
创建类时,括号里的object表示的是继承自object
3.对象
当你将一个类“实例化”以后,你就得到了一个对象(object)
实现实例化的方法,就是像调用函数一样地调用一个类:
thing = MyStuff()
thing.apple()
print thing.tangerine
第一行代码就是“实例化”操作,这和调用函数很相似。然而,当你进行实例化操作时,Python 在背后class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
输出结果
Happy birthday to you I don't want to get sued So I'll stop right there They rally around the family With pockets full of shells
## Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
class Dog(Animal):
def __init__(self, name):
self.name = name
class Person(object):
def __init__(self, name):
self.name = name
self.pet = None #确保类的 self.pet 属性被设置为 None
class Employee(Person):
def __init__(self, name, salary):
super(Employee, self).__init__(name)
self.salary = salary
class Parent(object):
def implicit(self):
print "PARENT implicit()"
class Child(Parent):
pass
dad = Parent()
son = Child()
dad.implicit()
son.implicit()
class Child: 中的pass是在Python中创建空的代码区块的方法。这样就创建了一个叫Child的类,但没有在里边定义任何细节。在这里它将会从它的父类中继承所有的行为。运行起来就是这样:
class Parent(object):
def override(self):
print "PARENT override()"
class Child(Parent):
def override(self):
print "CHILD override()"
dad = Parent()
son = Child()
dad.override()
son.override()
这里我在两个类中都定义了一个叫override的函数,我们看看运行时会出现什么情况。
class Parent(object):
def altered(self):
print "PARENT altered()"
class Child(Parent):
def altered(self):
print "CHILD, BEFORE PARENT altered()"
super(Child, self).altered()
print "CHILD, AFTER PARENT altered()"
dad = Parent()
son = Child()
dad.altered()
son.altered()
重要的是 9 到 11 行,当调用 son.altered() 时:
class Other(object):
def override(self):
print "OTHER override()"
def implicit(self):
print "OTHER implicit()"
def altered(self):
print "OTHER altered()"
class Child(object):
def __init__(self):
self.other = Other()
def implicit(self):
self.other.implicit()
def override(self):
print "CHILD override()"
def altered(self):
print "CHILD, BEFORE OTHER altered()"
self.other.altered()
print "CHILD, AFTER OTHER altered()"
son = Child()
son.implicit()
son.override()
son.altered()