python学习笔记6
类和对象的成员分析
类和对象都可以存储成员,成员可以归类所有,也可以归对象所有类存储成员是可以使用的是与类关联的一个对象独享存储成员是存储在当前对象中对象访问一个成员是,如果对象中没有该成员,尝试访问类中的同名。如果对象中有此成员,一定使用对象中的成员。创建对象的时候,类中的成员不会放入对象当中,而是得到一个空对象,没有成员通过对象对类中成员重新赋值或者通过对象添加成员时,对应成员会保存在对象中,而不会修改类成员变量
class Student():
name
= "dana"
age
= 18
Student
.__dict__
a
= Student
()
a
.__dict__
print(a
.name
)
dana
class A():
name
= "dana"
age
= 18
def say(self
):
self
.name
= "aaaa"
self
.age
= 200
print(A
.name
)
print(A
.age
)
print("*" * 20)
print(id(A
.name
))
print(id(A
.age
))
print("*" * 20)
a
=A
()
print(A
.name
)
print(A
.age
)
print(id(a
.name
))
print(id(a
.age
))
dana
18
********************
2069773571776
140730896455008
********************
dana
18
2069773571776
140730896455008
print(A
.name
)
print(A
.age
)
print("*" * 20)
print(id(A
.name
))
print(id(A
.age
))
print("*" * 20)
a
=A
()
print(A
.__dict__
)
print(a
.__dict__
)
a
.name
= "yaona"
a
.age
= 16
print(a
.__dict__
)
print(a
.name
)
print(a
.age
)
print(id(a
.name
))
print(id(a
.age
))
dana
18
********************
2069773571776
140730896455008
********************
{'__module__': '__main__', 'name': 'dana', 'age': 18, 'say': <function A.say at 0x000001E1E8217EA0>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
{}
{'name': 'yaona', 'age': 16}
yaona
16
2069773965776
140730896454944
关于self
self在对象的方法中表示当前对象本身,如果通过对象调用一个方法。那么该对象会自动传入到当前方法的第一个参数中self并不是关键字,只是一个用于接受对象的普通参数,理论上可以用任何一个普通变量名代替方法中有self形参的方法成为非绑定类的方法,可以通过对象访问,没有self的是绑定类的方法,只能通过类访问使用类访问绑定类的方法时,如果类方法中需要访问当前类的成员,可以通过__class__成员名来访问
class Student():
name
= "dana"
age
= 18
def say(self
):
self
.name
= "aaaa"
self
.age
= 200
print("My name is {0}".format(self
.name
))
print("My age is {0}".format(self
.age
))
def sayAgain(s
):
print("My name is {0}".format(s
.name
))
print("My age is {0}".format(s
.age
))
yueyue
= Student
()
yueyue
.say
()
yueyue
.sayAgain
()
My name is aaaa
My age is 200
My name is aaaa
My age is 200
class Teacher():
name
= "dana"
age
= 40
def say(self
):
self
.name
= "yaona"
self
.age
= 200
print("My name is {0}".format(self
.name
))
print("My age is {0}".format(__class__
.age
))
def sayAgain():
print(__class__
.name
)
print(__class__
.age
)
print("Hello ,nice to see you again")
t
= Teacher
()
t
.say
()
Teacher
.sayAgain
()
My name is yaona
My age is 200
dana
40
Hello ,nice to see you again
class A():
name
= "liuying"
age
= 18
def __init__(self
):
self
.name
= "aaaa"
self
.age
= 200
def say(self
):
print(self
.name
)
print(self
.age
)
class B():
name
= "bbbb"
age
= 90
a
= A
()
a
.say
()
A
.say
(a
)
A
.say
(A
)
A
.say
(B
)
aaaa
200
aaaa
200
liuying
18
bbbb
90
面向对象的三大类型
封装继承多态
封装
封装就是对对象中的成员进行访问限制
封装的三个级别:
公开:public受保护的:protected私有的:private _ public protected private 不是关键字
判别对象的位置
对象内部对象外部子类中
私有
私有成员是最高级别的封装,只能在当前类或对象中访问
在成员前面添加两个下划线即可
class Person():
# name是共有的成员
name = "liuying"
#__age 是私有成员
__age = 18
python 的私有不是真的私有,是一种称为 name mangling 的改名策略,
可以使用对象.__classname__attributename访问
受保护的封装 protected
受保护的封装是将对象成员进行一定级别的封装,然后,在类中或者子类中都可以进行访问,但是,在对象外部不可以。封装方法:在成员名称前添加一个下划线即可
公开的、公共的:public
公共的封装实际对成员没有任何操作,任何地方都可以访问
class Person():
name
= "liuying"
__age
= 18
p
= Person
()
print(p
.name
)
print(p
.__age
)
p
._Person__age
= 19
print(p
._Person__age
)
liuying
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-40-1823e1a3e23c> in <module>
11 #__age 是私有成员
12 # 注意报错信息
---> 13 print(p.__age)
AttributeError: 'Person' object has no attribute '__age'
print(Person
.__dict__
)
p
._Person__age
= 19
print(p
._Person__age
)
{'__module__': '__main__', 'name': 'liuying', '_Person__age': 18, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
19
继承
继承就是一个类可以获得另外一个类中的成员属性和成员方法
需要满足is A 关系,子类一定是父类的一个子集,比如狗是动物的一个子类。 作用:减少代码,增加代码的复用功能,同时可以设置类与类直接的关系继承与被继承的概念:
被继承的类称为父类,也叫基类,也叫超类用于继承的类,叫子类,也叫派生类,继承与被继承一定存在一个 is - A 关系 语法如下特征:
所有的类都继承自object,即所有的类都是它的子类子类一旦继承父类,则可以使用父类中除私有成员外的所有内容子类继承父类后并没有将父类成员完全赋值到子类中,而是通过引用关系访问调用子类中可以定义独有的成员属性和方法子类中定义的成员和父类如果相同,则优先使用子类成员子类中如果想扩充父类的方法,可以在定义新方法的同时访问父类成员来进行代码复用,
可以使用父类名.父类成员 的格式来调用父类成员,也可以使用super().父类成员的格式来调用 继承变量函数的查找顺序问题
优先查找自己的变量没有则查找父类构造函数如果本类中没有定义,则自动查找父类构造函数如果本类有定义,则不再继续向上查找 构造函数
是一类特殊的的函数,在类进行实例化之前进行调用如果定义了构造函数而实例化时使用构造函数,不查找父类构造函数如果没有定义,则自动查找父类构造函数如果子类没定义,父类构造函数带参数,则构造对象应该按父类参数进行构造 super
super不是一个关键字,而是一个类super的作用是获取MRO列表中的第一个类super 与父类没有任何实质性关系,但通过super可以调用到父类super使用两个方法,参见在构造函数中调用父类的构造函数
class Person():
name
= "小明"
age
= 0
__score
= 0
_petname
= "sex"
def sleep(self
):
print("sleep... ...")
class Teacher(Person
):
teacher_id
= "9527"
def make_test(self
):
print("attention")
t
= Teacher
print(t
.name
)
print(t
._petname
)
t
.sleep
(t
)
print(t
.teacher_id
)
t
.make_test
(t
)
小明
sex
sleep... ...
9527
attention
class Person():
name
= "小明"
age
= 0
__score
= 0
_petname
= "sex"
def sleep(self
):
print("sleep... ...")
class Teacher(Person
):
name
= "dana"
teacher_id
= "9527"
def make_test(self
):
print("attention")
t
= Teacher
print(t
.name
)
dana
class Person():
name
= "小明"
age
= 0
__score
= 0
_petname
= "sex"
def sleep(self
):
print("sleep... ...")
def work(self
):
print("make some money")
class Teacher(Person
):
name
= "dana"
teacher_id
= "9527"
def make_test(self
):
print("attention")
def work(self
):
super().work
(self
)
self
.make_test
(self
)
t
= Teacher
t
.work
(t
)
make some money
attention
class Dog():
def __init__(self
):
print("I am init in dog")
kaka
= Dog
()
I am init in dog
class Animel():
pass
class PaxingAni(Animel
):
pass
class Dog(PaxingAni
):
def __init__(self
):
print("I am init in dog")
kaka
= Dog
()
I am init in dog
class Animel():
def __init__(self
):
print("Animel")
class PaxingAni(Animel
):
def __init__(self
):
print("Paxing Dongwu")
class Dog(PaxingAni
):
def __init__(self
):
print("I am init in dog")
kaka
= Dog
()
class Cat(PaxingAni
):
pass
c
= Cat
()
I am init in dog
Paxing Dongwu
class Animel():
def __init__(self
):
print("Animel")
class PaxingAni(Animel
):
def __init__(self
,name
):
print("Paxing Dongwu {0}".format(name
))
class Dog(PaxingAni
):
def __init__(self
):
print("I am init in dog")
d
= Dog
()
class Cat(PaxingAni
):
pass
c
= Cat
()
I am init in dog
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-30-439aa10dccd9> in <module>
23 # 此时,由于Cat没有构造函数,则向上查找
24 # 因为PaxingAni的构造函数需要两个参数,实例化的时候只给了一个,报错
---> 25 c = Cat()
TypeError: __init__() missing 1 required positional argument: 'name'
class Animel():
def __init__(self
):
print("Animel")
class PaxingAni(Animel
):
pass
class Dog(PaxingAni
):
pass
d
= Dog
()
class Cat(PaxingAni
):
pass
c
= Cat
()
Animel
Animel
print(type(super))
print(help(super))
<class 'type'>
Help on class super in module builtins:
class super(object)
| super() -> same as super(__class__, <first argument>)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2) -> bound super object; requires issubclass(type2, type)
| Typical use to call a cooperative superclass method:
| class C(B):
| def meth(self, arg):
| super().meth(arg)
| This works for class methods too:
| class C(B):
| @classmethod
| def cmeth(cls, arg):
| super().cmeth(arg)
|
| Methods defined here:
|
| __get__(self, instance, owner, /)
| Return an attribute of instance, which is of type owner.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __self__
| the instance invoking super(); may be None
|
| __self_class__
| the type of the instance invoking super(); may be None
|
| __thisclass__
| the class invoking super()
None
super
super不是一个关键字,而是一个类super的作用是获取MRO列表中的第一个类super 与父类没有任何实质性关系,但通过super可以调用到父类super使用两个方法,参见在构造函数中调用父类的构造函数
class A():
pass
class B(A
):
pass
print(A
.__mro__
)
print(B
.__mro__
)
(<class '__main__.A'>, <class 'object'>)
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
单继承和多继承
单继承:每一个类只能继承一个类
多继承:每个类允许继承多个类
单继承和多继承的优缺点
单继承
优点:传承有序逻辑清晰语法简单隐患少缺点:功能不能无限拓展,只能在在当前唯一的继承链中拓展 多继承
优点:类的功能拓展方便缺点:继承关系混乱
菱形继承和钻石继承
多个子类继承继承自同一个父类,这些子类由被同一个类继承,于是继承关系图形成一个菱形图谱MRO就是多继承中,用于保存继承顺序的一个列表python本身采用C3算法来保存多继承的菱形继承计算的结果MRO列表的计算原则:
子类永远在父类前面如果多个父类,则根据继承语法中括号类的书写顺序存放如果多个类继承了同一个父类,孙子类中只会选取继承语法括号中第一个父类的父亲
class Fish():
def __init__(self
,name
):
self
.name
= name
def swim(self
):
print("i am swimming")
class Bird():
def __init__(self
,name
):
self
.name
= name
def fly(self
):
print("i am flying")
class Person():
def __init__(self
,name
):
self
.name
= name
def work(self
):
print("working")
class SuperMan(Person
,Bird
,Fish
):
def __init__(self
,name
):
self
.name
= name
class SwinMan(Person
,Fish
):
def __init__(self
,name
):
self
.name
= name
s
= SuperMan
("yueyue")
s
.fly
()
s
.swim
()
class Student(Person
):
def __init__(self
,name
):
self
.name
= name
stu
= Student
("yueyue")
stu
.work
()
i am flying
i am swimming
working
class A():
pass
class B(A
):
pass
class C(A
):
pass
class D(B
,C
):
pass
构造函数
在对象进行实例化的时候,系统自动调用的一个函数叫构造函数,通常此函数用来对实例对象进行初始化,故名构造函数
class Person():
def __init__(self
):
self
.name
= "NoName"
self
.age
= 18
self
.address
= "Chongqing"
print("In init func")
p
= Person
()
In init func
NoName
多态
多态就是同一个对象在不同情况下有不同的状态出现
多态不是语法,是一种设计思想
多态性:一种调用方式,不同的执行效果
多态:同一种事物的多种形态,比如动物分为人,狗,猪类
Mixin设计模式
主要采用多继承方式对类的功能进行拓展只是功能的增加,不改变种族。
我们使用多继承语法来实现Mixin
使用mixin实现多继承的时候非常小心
首先他必须表示某一单一功能,而不是某个物品职责必须单一,如果有多个功能,则写多个MixinMixin不能依赖子类的实现子类即使没有继承mixin类,照样能够工作,只是缺少了某个功能
优点
使用mixin可以在不对类进行任何修改的情况下,扩充功能可以方便的组织和维护不同功能组件的划分可以避免创建很多新的类,导致类的继承混乱
类相关函数
issubclass 检测一个类是不是另外一个类的子类
class A():
pass
class B(A
):
pass
class C():
pass
print(issubclass(B
,A
))
print(issubclass(C
,A
))
print(issubclass(B
,object))
True
False
True
isinstance:检测一个对象是否是一个类的实例
class A():
pass
a
= A
()
print(isinstance(a
,A
))
print(isinstance(A
,A
))
True
False
hasattr:检测一个对象是否有成员xxx
class A():
name
= "NoName"
a
= A
()
print(hasattr(a
,"name"))
print(hasattr(a
,"age"))
True
False
getattr: get attributesetattr: set attributedelattr: delete attributedir :获取对象的成员列表
class A():
pass
dir(A
)
a
= A
()
dir(a
)
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__']