引用模块练习代码
mystuff.py
def apple():
print("It's an apple.")
ex35.py
import mystuff
mystuff.apple()
运行结果
PS D:\pystudy> & D:/anaconda3/python.exe d:/pystudy/ex35.py
It's an apple.
类:用来告诉python创建新类型的东西
对象:最基本的东西或某样东西的实例
练习代码①
#类
class MyStuff(object):
#对空对象进行初始化操作,self就是那个空对象
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print("I AM CLASSY APPLES!")
#对象
#实例化操作:
#①Python查找MyStuff()类
#②创建空对象
#③检查__init__()函数的存在并对空对象进行初始化
#④将新建的对象赋给变量
thing = MyStuff()
thing.apple()
print(thing.tangerine)
运行结果①
PS D:\pystudy> & D:/anaconda3/python.exe d:/pystudy/ex36.py
I AM CLASSY APPLES!
And now a thousand years between
练习代码②
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()
运行结果②
PS D:\pystudy> & D:/anaconda3/python.exe d:/pystudy/ex3.py
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
对象、类及从属关系
class Person(object):
def __init__(self, name):
self.name = name
self.pet = None
class Employee(Person):
def __init__(self, name, salary):
super(Employee,self).__init__(name)
self.salary = salary
super(type[,object-orobject])
type:类
可选参数:对象或类,一般是self,可选参数
返回值super object:代理对象
详解