思维导图
基础概念讲解
对象是什么
- 对象 =属性 +方法
对象是类的实例。换句话说,类主要定义对象的结构,然后我们以类为模板创建对象。类不但包含方法定义,而且还包含所有实例共享的数据。
封装:信息隐蔽技术
使用关键字 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