python打卡学习7

思维导图

来源于别的网站的思维导图

基础概念讲解

对象是什么

  • 对象 =属性 +方法

对象是类的实例。换句话说,类主要定义对象的结构,然后我们以类为模板创建对象。类不但包含方法定义,而且还包含所有实例共享的数据。

封装:信息隐蔽技术

使用关键字 class 定义 Python 类,关键字后面紧跟类的名称、分号和类的实现

继承

  • 继承:子类自动共享父类之间数据和方法的机制

多态

  • 多态:不同对象对同一方法响应不同的行动

self

  • 相当于C++中this指针
  • 类的方法与普通的函数只有一个特别的区别 —— 它们必须有一个额外的第一个参数名称(对应于该实例,即该对象本身),按照惯例它的名称是 self。在调用方法时,我们无需明确提供与参数 self 相对应的参数。

公有变量和私有变量

class JustCounter:
    __secreCount =0
    publicCount =0
    def count(self):
        self.__secreCount+=1
        self.publicCount +=1
        print(self.__secreCount)
counter =JustCounter()
print(counter.count())
counter.count()
print(counter.publicCount)
print(counter.__secreCount)
# 1
# None
# 2
# 2
# AttributeError: 'JustCounter' object has no attribute '__secreCount'

变量中变成私有变量只需要在前面加__

  • 还可以在公有变量中调用私有变量
class Site:
    def __init__(self,name,url):
        self.name =name # public
        self.__url =url # private

    def __foo(self):
        print('这是私有方法')
    
    def foo(self):
        print('这是公有方法')
        self.__foo()
Harr =Site('Harr','www.baidu.com')
# print(help(Harr))
print(Harr.foo())
print(Harr.__foo())
# 这是公有方法
# 这是私有方法
# None
# tributeError: 'Site' object has no attribute '__foo'

如果子类定义与父类相同的方法或者属性,则会自动覆盖父类的方法或属性

class People:
    name =''
    age =0
    __weight =0
    def __init__(self,n,a,w):
        self.name =n
        self.age =a
        self.__weight =w
    def speak(self):
        print('%s是我的名字,我的年龄是%d '%(name,age))
class Student(People):
    grade =0
    def __init__(self,n,a,w,g):
        People.__init__(self,n,a,w)
        self.grade  =g
    def speak(self):
        print('我的名字是%s,我今年%d岁了,我读%d年级'%(self.name,self.age,self.grade))
        
student =Student("小明",16,140,9)
student.speak()

class Speaker:
    topic =''
    name =''
    def __init__(self,n,t):
        self.name =n
        self.topic =t 
        
    def speak(self):
        print('my name is %s and my topic is %s'%(self.name,self.topic))
        
# 多重集成
class Sample01(Student,Speaker):
#     a =''
    def __init__(self,n,a,w,g,t):
        Student.__init__(self,n,a,w,g)
        Speaker.__init__(self,n,t)
        
test =Sample01('Harry',18,160,9,'hello my world')
    
test.speak()
class Sample02(Speaker,Student):
    def __init__(self,n,a,w,g,t):
        Speaker.__init__(self,n,t)
        Student.__init__(self,n,a,w,g)
test2 =Sample02('Harry',18,160,9,"Hello my world")
test2.speak()
# 我的名字是小明,我今年16岁了,我读9年级
# 我的名字是Harry,我今年18岁了,我读9年级
# my name is Harry and my topic is Hello my world

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值