理论学习只能入门,真正学会还得实操
`
第八章 类与对象
🔥系列专栏:极简python
🎉欢迎关注🔎点赞👍收藏⭐️留言📝
📆首发时间:🌴2022年9月25日🌴
🍭作者水平很有限,如果发现错误,还望告知,感谢!
用class定义类,类名首字母通常大写,
类对象中:变量是属性,函数是方法
当调用一个类后,会自动调用其中的属性,但是方法按照用户的需求来
搞不清楚啥是啥?,没有关系
一句话:万物皆对象
一、
class Hahaha:
print("哈哈哈")
def heihei():
print("嘿嘿")
//下面这两个输出调用语句可以删掉,看看有什么变化
print(Hahaha.heihei)
Hahaha.heihei()
self参数
self作为第一个参数,在实例化的过程中,后面更改的参数会代替self进入到函数的运行中
class Hahaha:
def heihei(self):
self.color="yellow"
print(self.color)
a=Hahaha()
a.heihei()
初始化函数
普通的类中函数不会自行调用,初始化函数会自行调用
class Hahaha:
def name(self):
self.color="yellow"
print(self.color)
a=Hahaha()
class Hahaha:
def __init__(self):
self.color="yellow"
print(self.color)
a=Hahaha()
对比一下这两个,实际运行一下
单继承
只要在子孙类的括号中加上爸爸的名字,她就可以调用爸爸的方法属性等
注意别忘了括号就行
class hahaha:
lsp="you"
def __init__(self):
self.color="yellow"
print(self.color)
def name(self):
self.color=123
print(self.color)
class Son_hahaha(hahaha):
pass
b=Son_hahaha()
b.lsp
b.name()
多继承
class A:
lsp="you"
def __init__(self):
self.color="yellow"
print(self.color)
def name(self):
self.color=123
print(self.color)
class B(A):
aaa="ccc"
class C(B):
pass
c=C()
c.name()
print(c.aaa)
重写
如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
注意以下几点:
只有实例才可调用,属性不可调用
class a(object):
zz=11
def aa(self):
sb=12
class b(a):
xx=22
pass
c=b
c.sb
报错信息:
AttributeError: type object 'b' has no attribute 'sb'
没有sb这个东西,就是因为他不是一个实例
class a(object): //object所有类的父类,默认所有的类都继承至Object类规定了类的结构,加载方式,常用函数
zz=11
def __init__(self):
self.sb="哈哈"
def zzz(self):
print(self.sb)
class b(object):
xx=22
def __init__(self):
self.sb="嘿嘿"
def zzz(self):
print(self.sb)
class c(a,b):
cc=33
def __init__(self):
pass
self.hahah="呵呵"
def from_c(self):
self.__init__()
print(self.hahah)
def from_a(self):
a.__init__(self)
a.zzz(self)
def from_b(self):
b.__init__(self)
b.zzz(self)
zhongqiu=a()
daqiu=b()
xiaoqiu=c()
#daqiu.zzz()
#xiaoqiu.zzz()
#zhongqiu.zzz()
xiaoqiu.from_c()