【Python】“笨办法”学Python3-模块、类、对象

引用模块练习代码

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:代理对象
详解

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值