发布时间:2019-06-30 16:53:12编辑:auto阅读(1936)
python学习笔记12-python面向对象
python一切皆对象
一、基本概念
1、面向对象和面向过程
面向对象编程:C++,Java,Python
面向过程编程:函数式编程,C程序等
2、类和对象
类:是对事物的抽象,比如:人类,球类
对象:是类的一个实例,比如:足球,篮球,对象就是对类的实例化
属性:五官,眼,鼻子,理解为一个变量,静态属性
方法:对人来说,吃穿住行,理解为一个函数,动态方法
实例说明:球类可以对球的特征和行为进行抽象,然后可以实例化一个真实的球实体出来
3、为什么要使用面向对象?
面向对象的主要思想是:
封装
继承
多态
这种思想方便解决较为复杂的项目,且维护起来比较容易
二、Python类定义
1、类定义(封装)
类把需要的变量和函数组成在一起,这种包含称为“封装”
class A(object):
A是类名:数字,字母和下划线组成,不能是数字开头,首字母大写
变量,小写,两个单词,中间下划线
函数,如果是两个单词,首字母小写,第二个字符以后首字母大写
2、类的结构:
class 类名
成员变量-属性
成员函数-方法
调用对象的方法,其实就是调用对象的一个函数
3、类的创建
class MyClass(object):
def fun(self):
print "I am function"
类的方法中至少有一个参数self
4、类的创建实例
[root@133 class]# vim class1.py #!/usr/bin/python class People(object): color = 'yello' #定义静态属性 def think(self): #定义动态方法,必须要有一个self self.color = 'black' #函数内也可以调用类的属性,还可以重新赋值,但是需要使用self print "I am a %s" % self.color print "I am a thinker" people = People() #类的实例化,就是把类赋值给一个变量,这个变量就是这个对象,通过这个对象,去调用他的属性和方法 print people.color #color是属性,不用括号() people.think() #think是方法,需要带括号() [root@133 class]# python class1.py yello I am a black I am a thinker
5、对象的创建
创建对象的过程称之为实例化,当一个对象被创建后,包含三个方面的特性,对象句柄,属性和方法
句柄用于区分不同的对象 people
对象的属性color和方法think与类中的成员变量和成员函数对应
obj = MyClass() //创建类的一个实例(对象),通过对象来调用方法和属性
6、类的属性,按照使用范围分为公有属性和私有属性,
公有属性,类中、类外都能被调用
私有属性,不能再类外以及被类外其他函数调用,以__(双下划线)开始的成员变量就是私有属性
可以通过instance._classname__attribute方式访问。前面是单下划线,后边是双下划线。
内置属性:由系统在定义类的时候默认添加的,由前后双下划线构成,__dict__ , __module__。
[root@133 class]# vim class1.py
#!/usr/bin/python
class People(object):
    color = 'yello'
    __age = 30      #添加了私有属性__age = 30
    def think(self):
        self.color = 'black'
        print "I am a %s" % self.color
        print "I am a thinker"
        print self.__age  #私有属性__age = 30类内部可以调用
people = People()
print people.color
people.think()
people.__age #私有属性__age = 30类外部不能使用
[root@133 class]# python class1.py 
yello
I am a black
I am a thinker
30           #私有属性__age = 30类内部可以调用
Traceback (most recent call last):   #私有属性__age = 30类外部不能使用
  File "class1.py", line 15, in <module>
    people.__age
AttributeError: 'People' object has no attribute '__age'#报错,对象people没有属性__age
[root@133 class]# vim class1.py
#!/usr/bin/python
class People(object):
    color = 'yello'
    __age = 30
    def think(self):
        self.color = 'black'
        print "I am a %s" % self.color
        print "I am a thinker"
        print self.__age
people = People()
print people.color
people.think()
print people._People__age   #在类外调用类的私有属性,但是不建议这样做,类People前面是单下划线,后边是双下划线
[root@133 class]# vim class1.py
#!/usr/bin/python
class People(object):
    color = 'yello' #内置属性
    __age = 30
    def think(self):
        self.color = 'black'
        print "I am a %s" % self.color
        print "I am a thinker"
        print self.__age
people = People()
print people.color
people.think()
print people.__dict__  #通过对象调用内置属性,区别类调用内置属性,
[root@133 class]# python class1.py 
yello
I am a black
I am a thinker
30
{'color': 'black'}  #生成字典,内置属性
[root@133 class]# vim class1.py
#!/usr/bin/python
#coding:utf-8   #支持中文,或者coding:utf8  或者encoding:utf-8 或者 # -*- encoding:utf-8 -*-
class People(object):
    color = 'yello'
    __age = 30
    def think(self):
        self.color = 'black'
        print "I am a %s" % self.color
        print "I am a thinker"
        print self.__age
people = People()
people.color = '白种人'
print people.color
people.think()
print people.__dict__
print '#' *30
print People.color
[root@133 class]# python class1.py 
白种人   
I am a black
I am a thinker
30
{'color': 'black'}
##############################
yello
[root@133 class]# vim class1.py
#!/usr/bin/python
#coding:utf-8
class People(object):
    color = 'yello'
    __age = 30
    def think(self):
        self.color = 'black'
        print "I am a %s" % self.color
        print "I am a thinker"
        print self.__age
people = People()
people.color = '白种人'
print people.color
people.think()
print people.__dict__
print '#' *30
print People.color
print People.__dict__  #通过类来调用内置属性,会把系统内置属性打印出来,非常之多
[root@133 class]# python class1.py   
白种人
I am a black
I am a thinker
30
{'color': 'black'}
##############################
yello
{'__module__': '__main__', 'color': 'yello', '__doc__': None, '__dict__': <attribute '__dict__' of 'People' objects>, '_People__age': 30, '__weakref__': <attribute '__weakref__' of 'People' objects>, 'think': <function think at 0x7f7c3b5c6758>}7、类的方法
方法的定义和函数一样,动态方法需要self作为第一个参数,静态方法没有self参数
类的方法为:
公有方法:在类中和类外都能够被调用的方法
私有方法:不能被类的外部调用,在方法前面加上"__"双下划线就是私有方法。
类方法 :被classmethod()函数处理过的函数,能够被类直接调用,也能被对象所调用(是继承的关系)
静态方法:通过staticmethod()定义,相当于“全局函数”,可以被类直接调用,可以被所有的实例化后的对象共享,静态方法没有self参数。
装饰器:
@classmethod
@staticmethod
self参数:用于区分函数和类(必须有一个self)的方法,self参数表示执行对象本身。
(1)公有方法:
[root@133 class]# vim class1.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 def think(self): #公有方法think self.color = 'black' print "I am a %s" % self.color print "I am a thinker" print self.__age def test(self): #定义公有方法test,在类的内部调用公有方法think self.think() #在类People的内部调用 jack = People() #实例化类People jack.test() #在类People的外部调用 [root@133 class]# python class1.py I am a black I am a thinker 30
(2)私有方法:
#在类的内部调用私有方法,ok [root@133 class]# vim class1.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 def think(self): self.color = 'black' print "I am a %s" % self.color print "I am a thinker" print self.__age def __talk(self): #定义私有方法 print "I am talking" def test(self): self.think() self.__talk() #在类的内部调用私有方法,ok jack = People() jack.test() [root@133 class]# python class1.py I am a black I am a thinker 30 I am talking #在类的内部调用私有方法,ok #在类的外部调用类的私有方法,失败,报错如下 [root@133 class]# vim class1.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 def think(self): self.color = 'black' print "I am a %s" % self.color print "I am a thinker" print self.__age def __talk(self): print "I am talking" def test(self): self.think() self.__talk() jack = People() jack.test() jack.__talk() #在类的外部调用类的私有方法,失败,报错如下 [root@133 class]# python class1.py I am a black I am a thinker 30 I am talking Traceback (most recent call last): File "class1.py", line 19, in <module> jack.__talk() AttributeError: 'People' object has no attribute '__talk' #如果我非要在类外调用类的私有方法,怎么办?参考在类外调用类的属性,使用jack._People__talk() [root@133 class]# python class1.py I am a black I am a thinker 30 I am talking I am talking [root@133 class]# vim class1.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 def think(self): self.color = 'black' print "I am a %s" % self.color print "I am a thinker" print self.__age def __talk(self): print "I am talking" def test(self): self.think() self.__talk() jack = People() jack.test() jack._People__talk()#如果我非要在类外调用类的私有方法,怎么办?参考在类外调用类的属性,类People前面是单下划线,后边是双下划线
(3)类方法:
一般方法都是经过实例化的对象去调用,类不允许直接调用,如果想直接调用,怎么办?
被classmethod()函数处理过的函数,能够被类所调用,也能被对象所调用(是继承的关系)
[root@133 class]# vim class1.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 def think(self): self.color = 'black' print "I am a %s" % self.color print "I am a thinker" print self.__age def __talk(self): print "I am talking" def test(self): self.think() self.__talk() jack = People() jack.test() jack._People__talk() People.think() #通过类直接调用方法,没有通过对象调用,报错如下 Traceback (most recent call last): File "class1.py", line 20, in <module> People.think() TypeError: unbound method think() must be called with People instance as first argument (got nothing instead) [root@133 class]# 如果想去调用,被classmethod()函数处理过的函数,能够被类所调用 [root@133 class]# vim class1.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 def think(self): self.color = 'black' print "I am a %s" % self.color print "I am a thinker" print self.__age def __talk(self): print "I am talking" def test(self): #定义一个类方法,通过类来访问资源占用资源少,很多信息并没有被加载到内存中,使用的时候才会加载 print 'Testing' cm = classmethod(test) #定义一个类方法,cm是经过classmethod()函数处理 jack = People() jack.test() jack._People__talk() People.cm() #类直接调用类方法,输出结果正常,没有报错(一般只有对象才能直接调用类的方法) [root@133 class]# python class1.py Testing I am talking Testing #类直接调用类方法,输出结果正常, [root@133 class]# vim class1.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 def think(self): self.color = 'black' print "I am a %s" % self.color print "I am a thinker" print self.__age def __talk(self): print "I am talking" def test(self): print self.color cm = classmethod(test) #定义类方法cm jack = People() jack.test() jack._People__talk() People.cm() [root@133 class]# python class1.py yello I am talking yello #通过类调用类方法打印的类的属性,color = yello,输出正常 #用装饰器@classmethod申明类方法 [root@133 class]# vim class1.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 def think(self): self.color = 'black' print "I am a %s" % self.color print "I am a thinker" print self.__age def __talk(self): print "I am talking" @classmethod #用装饰器@classmethod申明类方法,只对下面一个函数起作用 def test(self): print "this is class method" jack = People() People.test() #类方法可以被类直接调用,一般都是被对象调用 [root@133 class]# python class1.py this is class method
(4)静态方法:
[root@133 class]# vim class1.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 def think(self): self.color = 'black' print "I am a %s" % self.color print "I am a thinker" print self.__age def __talk(self): print "I am talking" def test(): #test()是静态方法,没有self参数 print "this is func" sm = staticmethod(test) # jack = People() jack.sm() People.sm() [root@133 class]# python class1.py this is func this is func [root@133 class]# vim class1.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 def think(self): self.color = 'black' print "I am a %s" % self.color print "I am a thinker" print self.__age def __talk(self): print "I am talking" def test(): print "this is func" print People.color #调用类里面的其他成员属性,通过类.属性去调用 print People.__age #调用类里面的其他成员属性,通过类.属性去调用 sm = staticmethod(test) jack = People() jack.sm() [root@133 class]# python class1.py this is func yello 30 #用装饰器@staticmethod申明静态方法 [root@133 class]# vim class1.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 def think(self): self.color = 'black' print "I am a %s" % self.color print "I am a thinker" print self.__age def __talk(self): print "I am talking" @classmethod def test(self): print "this is class method" @staticmethod #用装饰器@staticmethod申明静态方法,只对下面一个函数起作用 def static(): print "this is static method" jack = People() People.static() [root@133 class]# python class1.py this is static method
(5)类的内置方法
所谓内部类,就是在类的内部定义的类,主要的目的是为了更好的抽象现实的世界。
例子:
汽车是个类,汽车的底盘,轮胎也可以抽象为类,将其定义到汽车中,则形成内部类,更好的描述汽车类,因为底盘,轮胎是汽车的一部分。
In [1]: import os In [2]: os.path.get() #os是外部类,path是内部类
内部类的实例化方法
方法1:直接使用外部类调用内部类
object_name=outclass_name.inclass_name()
[root@133 class]# vim neizhiclass.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 class Chinese(object): name = "I am chinese" print People.Chinese.name #直接使用外部类调用内部类 或者 print People.Chinese().name #通过对象对属性访问 [root@133 class]# python neizhiclass.py I am chinese [root@133 class]# vim neizhiclass.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 class Chinese(object): #定义的内部类 print "I am chinese" jack = People.Chinese() #直接使用外部类调用内部类 [root@133 class]# python neizhiclass.py I am chinese [root@133 class]# vim neizhiclass.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 class Chinese(object): #定义的内部类 name = "I am chinese" jack = People.Chinese() #直接使用外部类调用内部类 print jack.name #然后显示内置属性 [root@133 class]# python neizhiclass.py I am chinese
方法二2:先对外部类进行实例化,然后再实例化内部类
out_name = outclass_name()
in_name = out_name.inclass_name()
in_name.method()
#先对外部类进行实例化,然后再实例化内部类 [root@133 class]# vim neizhiclass.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yello' __age = 30 class Chinese(object): name = "I am chinese" ren = People() jack = ren.Chinese() print jack.name [root@133 class]# python neizhiclass.py I am chinese
(6)魔术方法 构造函数&析构函数
__str__(self)
构造函数与解析函数
构造函数:
用于初始化类的内部状态,Python提供的构造函数式__init__();
__init__()方法是可选的,如果没有提供,Python会给出一个默认的__init__方法
析构函数
用于释放对象占用的资源,Python提供的析构函数是:__del__();
__del__()也是可选的,如果不提供,则Python会在后台提供默认的析构函数
[root@133 class]# vim neizhiclass.py 
#!/usr/bin/python
#coding:utf-8
class People(object):
    color = 'yello'
    __age = 30
    class Chinese(object):
        name = "I am chinese"
ren = People()
print ren
[root@133 class]# python neizhiclass.py 
<__main__.People类 object at 0x7f10ce0ae7d0(内存地址)>  #打印一个对象
[root@133 class]# vim neizhiclass.py 
#!/usr/bin/python
#coding:utf-8
class People(object):
    color = 'yello'
    __age = 30
    class Chinese(object):
        name = "I am chinese"
    def __str__(self):
        return "this is a People class"
ren = People()
print ren
[root@133 class]# python neizhiclass.py 
this is a People class
[root@133 class]# vim neizhiclass.py 
#!/usr/bin/python
#coding:utf-8
class People(object):
    color = 'yello'
    __age = 30
    class Chinese(object):
        name = "I am chinese"
    def __str__(self):
        return "this is a People class"
    def __init__(self):  #用于初始化类的内部状态,类实例化的时候,自动执行
        self.color = 'black'
ren = People()
print ren.color  #对象访问返回初始化设置的black
print People.color#类访问时返回yellow
[root@133 class]# python neizhiclass.py 
black
yello
[root@133 class]# vim neizhiclass.py 
#!/usr/bin/python
#coding:utf-8
class People(object):
    color = 'yello'
    __age = 30
    class Chinese(object):
        name = "I am chinese"
    def __str__(self):
        return "this is a People class"
    def __init__(self,c='white'):
        self.color = c
ren = People()
print ren.color    #通过对象调用的属性变成了white,初始化完成的
print People.color #通过类调用的属性没有变化,都是yellow
[root@133 class]# python neizhiclass.py 
white
yello
[root@133 class]# vim neizhiclass.py 
#!/usr/bin/python
#coding:utf-8
class People(object):
    color = 'yello'
    __age = 30
    class Chinese(object):
        name = "I am chinese"
    def __str__(self):
        return "this is a People class"
    def __init__(self,c='white'):
        self.color = c
ren = People('green')  #初始化传的值被c接受了,通过对象去访问的值会根据传值改变
print ren.color
print People.color     #通过类去访问的值不变的
[root@133 class]# python neizhiclass.py 
green
yello
[root@133 class]# vim neizhiclass.py 
#!/usr/bin/python
#coding:utf-8
class People(object):
    color = 'yello'
    __age = 30
    class Chinese(object):
        name = "I am chinese"
    def __str__(self):
        return "this is a People class"
    def __init__(self,c='white'):
        self.color = c   #第一步,先赋值为green,然后赋值为black,
        self.think()
    def think(self):     #第二步,打印三行,
        self.color = "black"
        print "I am a %s " % self.color
        print "I am a thinker"
        print self.__age
ren = People('green')
print ren.color          #对象的值已经被修改为self.color = 'black'
print People.color       #类调用的是yellow
[root@133 class]# python neizhiclass.py 
I am a black 
I am a thinker
30
black
yello析构函数;释放资源,打开文件,链接都可以释放资源,脚本的最后
[root@133 class]# vim neizhiclass.py 
#!/usr/bin/python
#coding:utf-8
class People(object):
    color = 'yello'
    __age = 30
    class Chinese(object):
        name = "I am chinese"
    def __str__(self):
        return "this is a People class"
    def __init__(self,c='white'):
        print "Init...."
        self.color = c
        self.think()
        self.fd= open('/etc/hosts') #打开文件
    def think(self):
        self.color = "black"
        print "I am a %s " % self.color
        print "I am a thinker"
        print self.__age
    def __del__(self):    #定义del函数
        print "DEl....."
        self.fd.close()  #关闭文件
ren = People('green')
print ren.color
print People.color
print 'Main end'
[root@133 class]# python neizhiclass.py 
Init....
I am a black 
I am a thinker
30
black
yello
Main end
DEl.....  #在脚本的最后释放资源(7) Python垃圾回收机制
Python 采用垃圾回收机制来清理不再使用的对象,python提供gc模块释放不再使用的对象
Python采用“引用计数”的算法方式来处理回收,即:当某个对象在其作用域内不再被其他对象引用的时候,python就自动清除该对象
gc模块的collect()可以一次性收集所有待处理的对象gc.collect
[root@133 class]# vim neizhiclass.py 
#!/usr/bin/python
#coding:utf-8
import gc     #导入gc模块
class People(object):
    color = 'yello'
    __age = 30
    class Chinese(object):
        name = "I am chinese"
    def __str__(self):
        return "this is a People class"
    def __init__(self,c='white'):
        print "Init...."
        self.color = c
        self.think()
        self.fd= open('/etc/hosts')
    def think(self):
        self.color = "black"
        print "I am a %s " % self.color
        print "I am a thinker"
        print self.__age
    def __del__(self):
        print "DEl....."
        self.fd.close()
print gc.collect() #调用gc模块,打印结果,如果为0说明没有回收
ren = People('green')
print ren.color
print People.color
print 'Main end'
[root@133 class]# python neizhiclass.py 
0
Init....
I am a black 
I am a thinker
30
black
yello
Main end
DEl.....三、类的继承
继承是面向对象的重要特性之一;
继承关系,继承是相对两个类而言的父子关系,子类继承父类的所有公有属性和方法
继承实现了代码重用
1、使用继承
继承可以重用已经存在的数据和行为,减少代码的重复编写,Python在类名的后边使用的是一对括号来表示继承关系,括号中的类即为父类。
Class Myclass(ParentClass)
如果父类定义了__init__方法,子类必须显式调用父类的__init__方法:
ParentClass.__init__(self,[args...])
如果子类需要扩展父类的行为,可以添加__init__方法的参数
2、继承父类
class A:
def __init__(self):
print "enter A"
print "leave A"
class B(A):
def __init__(self)
print "enter B"
A.__init__(self)
print "leave B"
b = B()
[root@133 class]# vim test.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yellow' __age = 30 # print "I am chinese" name = "chinese" def think(self): print "I am a %s" % self.color print self.color print self.__age class Chinese(People): #子类Chinese直接继承父类People pass cn = Chinese() #实例化Chinese,生成对象cn print cn.name #调用父类的属性name cn.think() #调用父类的方法think [root@133 class]# python test.py chinese I am a yellow yellow 30 父类里面有构造函数,例如:__init__(包含属性) 那么子类能够调用父类的构造函数的属性呢? [root@133 class]# vim test.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yellow' __age = 30 # print "I am chinese" name = "chinese" def think(self): print "I am a %s" % self.color print self.color print self.__age def __init__(self): print "Init..." self.dwell = 'Earth' class Chinese(People): pass cn = Chinese() print cn.dwell cn.think() [root@133 class]# python test.py Init... Earth #打印了Earth,说明可以调用父类的构造函数的属性 I am a yellow yellow 30 如果父类定义了__init__方法,并且参数大于等于2,子类必须显式调用父类的__init__方法: [root@133 class]# vim test.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yellow' __age = 30 # print "I am chinese" name = "chinese" def think(self,c): #构造函数,传参数C,但是子类调用没有给两个参数会报错 print "I am a %s" % self.color print self.color print self.__age def __init__(self,c): print "Init..." self.dwell = 'Earth' class Chinese(People): pass cn = Chinese() print cn.dwell cn.think() [root@133 class]# python test.py Traceback (most recent call last): File "test.py", line 19, in <module> cn = Chinese() TypeError: __init__() takes exactly 2 arguments (1 given) #提示少了一个参数,怎么办?在子类中改写init 如果子类需要扩展父类的行为,可以添加__init__方法的参数 [root@133 class]# vim test.py #!/usr/bin/python #coding:utf-8 class People(object): color = 'yellow' __age = 30 # print "I am chinese" name = "chinese" def think(self): print "I am a %s" % self.color print self.color print self.__age def __init__(self, c): print "Init..." self.dwell = 'Earth' class Chinese(People): def __init__(self): People.__init__(self,'red') #与__init__(self, c)对应 pass cn = Chinese() print cn.dwell cn.think() [root@133 class]# python test.py Init... Earth I am a yellow yellow 30
3、使用Super函数继承父类
class A (object):
def __init__(self):
print "enter A"
print "leave A"
class B(A):
def __init__(self):
print "enter B"
super(B,self).__init__()
print "leave B"
b = B()
[root@133 class]# vim test.py
#!/usr/bin/python
#coding:utf-8
class People(object):
    color = 'yellow'
    __age = 30
    name = "chinese"
    def think(self):
        print "I am a %s" % self.color
        print self.color
        print self.__age
    def __init__(self, c):
        print "Init..."
        self.dwell = 'Earth'
class Chinese(People):
    def __init__(self):
        super(Chinese,self).__init__('red')#用super继承父类构造函数的__init__并重新赋值
       # People.__init__(self,'red')
    pass
cn = Chinese()
print cn.dwell
cn.think()
[root@133 class]# python test.py 
Init...
Earth
I am a yellow
yellow
30
[root@133 class]# vim test.py
#!/usr/bin/python
#coding:utf-8
class People(object):
    color = 'yellow'
    __age = 30
    name = "chinese"
    def think(self):            #父类定义了think方法
        print "I am a %s" % self.color
        print self.color
        print self.__age
    def __init__(self, c):
        print "Init..."
        self.dwell = 'Earth'
class Chinese(People):
    def __init__(self):
        super(Chinese,self).__init__('red')
#        People.__init__(self,'red')
    pass
    def think(self):                      #子类又重复定义了think方法
        print "This is method 1234"
cn = Chinese()
print cn.dwell
cn.think()
[root@133 class]# python test.py  
Init...
Earth
This is method 1234   #从结果知道最终调用的是子类的think方法,可以重复,重复就相当于重写了父类的方法或者属性python的构造函数是不是一定就是def __init__() 一定是用init表示吗?那我是不是可以理解为这是唯一的一个存在类里面的构造函数?
是的,__init__()属于类的内置方法,这些内置方法python已经定义好了。
4、多种继承
Python支持多重继承,即一个子类可以继承多个父类
语法:
class class_name(Parent_c1,Parent_c2,...)
注意:
当父类中出现多个自定义的__init__方法时候,多重继承只执行第一个类的__init__方法,其他不执行,如果想继承非第一个父类的属性和方法,需要显性的取调用。
[root@133 class]# vim test.py #!/usr/bin/python #coding:utf-8 class People(object): __age = 30 name = "chinese" def think(self): print "I am a %s" % self.color print "My home is %s " % self.dwell def __init__(self): print "Init..." self.dwell = 'Earth' color = 'yellow' class Martian(object): color = 'red' def __init__(self): self.dwell = 'Martian' class Chinese(Martian,People): #先继承Martian,后继承People pass cn = Chinese() cn.think() [root@133 class]# python test.py #打印结果是继承来自Martain I am a red My home is Martian [root@133 class]# python test.py Init... I am a red My home is Earth [root@133 class]# vim test.py #!/usr/bin/python #coding:utf-8 class People(object): __age = 30 name = "chinese" def think(self): print "I am a %s" % self.color print "My home is %s " % self.dwell def __init__(self): print "Init..." self.dwell = 'Earth' color = 'yellow' class Martian(object): color = 'red' def __init__(self): self.dwell = 'Martian' class Chinese(People,Martian): #People在前,Martain在后面,结果来自第一个父类People pass cn = Chinese() cn.think() [root@133 class]# vim test.py #!/usr/bin/python #coding:utf-8 class People(object): __age = 30 name = "chinese" def think(self): print "I am a %s" % self.color print "My home is %s " % self.dwell def __init__(self): print "Init..." self.dwell = 'Earth' color = 'yellow' class Martian(object): color = 'red' def __init__(self): self.dwell = 'Martian' class Chinese(People,Martian): #People在前面,理论子类应该继承该父类的属性,但是如果我想调用Martain的父类属性,就显示的调用,前后就无所谓了 def __init__(self): Martian.__init__(self) #这里显示调用Martain这个类,打印结果为red Martain pass cn = Chinese() print cn.dwell cn.think() [root@133 class]# python test.py Martian I am a red My home is Martian
5、类的属性-总结
类属性,也是公有属性
类的私有属性
对象的私有属性
内置属性
函数的局部变量
全局变量
[root@133 class]# vim test2.py 
#!/usr/bin/python
#coding:utf8
class MyClass(object):
    var1 = '类属性,类的公有属性var1'   #通过对象来访问
    __var2 = '类的私有属性__var2'       #对象默认不能访问,特殊方法,
    def func1(self):
        self.var3 = '对象的公有属性'          #通过对象访问,前提是对象调用一次这个方法
        self.__var4 = '对象的私有属性__var4'  #在类的外面通过对象默认不能访问,通过类可以访问
        var5 = '函数的局部变量'  #在类的外面通过对象默认不能访问,通过类可以访问
mc = MyClass()
print mc.var1                #对象访问类的公有属性,ok
print mc._MyClass__var2      #对象访问类的私有属性,默认不行,特殊方法ok,对象调用类才能访问
mc.func1()     #对象的方法,这里mc调用了func1()这个方法,mc才能访问func1里面的属性和方法,python一切皆对象
print mc.var3  #对象访问对象的公有属性,ok
print mc._MyClass__var4 #对象访问对象的私有属性,默认不能访问,通过特殊方法,对象调用类才能访问
[root@133 class]# python test2.py 
类属性,类的公有属性var1
类的私有属性__var2
对象的公有属性
对象的私有属性__var4
对象的属性只能是对象能访问,类不能访问对象的公有属性,类MyClass.var3,4,5报错
[root@133 class]# vim test2.py 
#!/usr/bin/python
#coding:utf8
class MyClass(object):
    var1 = '类属性,类的公有属性var1'
    __var2 = '类的私有属性__var2'
    def func1(self):
        self.var3 = '对象的公有属性'
        self.__var4 = '对象的私有属性__var4'
        var5 = '函数的局部变量'
mc = MyClass()
print mc.var1
print mc._MyClass__var2
mc.func1()#对象的方法,这里mc调用了func1()这个方法,mc才能访问func1里面的属性和方法,python一切皆对象
print mc.var3
print mc._MyClass__var4
print MyClass.var1    #类访问类的公有属性,ok,没有问题
#print MyClass.__var2 #类不能访问类的私有属性,报错没有这个类,结果省略
print MyClass.var3    #类不能访问对象的公有属性,对象的属性只能是对象能访问,直接报错,
注意:对象的属性只能是对象能访问,类不能访问,类MyClass访问var1,var2,var3都会报错
[root@133 class]# python test2.py 
类属性,类的公有属性var1
类的私有属性__var2
对象的公有属性
对象的私有属性__var4
类属性,类的公有属性var1
Traceback (most recent call last):
  File "test2.py", line 21, in <module>
    print MyClass.var3
AttributeError: type object 'MyClass' has no attribute 'var3'
注意:对象的属性定义在方法里面,类的属性定义在方法外
那么对象的属性,在类的内部可以调用吗? 可以
[root@133 class]# vim test2.py 
#!/usr/bin/python
#coding:utf8
class MyClass(object):
    var1 = '类属性,类的公有属性var1'
    __var2 = '类的私有属性__var2'
    def func1(self):
        self.var3 = '对象的公有属性'
        self.__var4 = '对象的私有属性__var4'
        var5 = '函数的局部变量'
    def func2(self):
        print self.var1
        print self.__var2
mc = MyClass()
mc.func2()#func2() #在类的内部,可以访问类的公有和私有属性,都可以访问
[root@133 class]# python test2.py 
类属性,类的公有属性var1
类的私有属性__var2
[root@133 class]# vim test2.py 
#!/usr/bin/python
#coding:utf8
class MyClass(object):
    var1 = '类属性,类的公有属性var1'
    __var2 = '类的私有属性__var2'
    def func1(self):
        self.var3 = '对象的公有属性'
        self.__var4 = '对象的私有属性__var4'
        
    def func2(self):
        print self.var1
        print self.__var2
        print self.var3  #调用对象的公有属性,ok,前提是调用一下func1()函数
        print self.__var4
mc = MyClass()
mc.func1()
mc.func2()#func2()在类的内部,可以在类的内部调用类的属性
[root@133 class]# python test2.py 
类属性,类的公有属性var1
类的私有属性__var2
对象的公有属性
对象的私有属性__var4
var5作为函数的局部变量,其他函数和类外部都不能被访问
内置属性
[root@133 class]# vim test2.py 
#!/usr/bin/python
#coding:utf8
class MyClass(object):
    var1 = '类属性,类的公有属性var1'
    __var2 = '类的私有属性__var2'
    def func1(self):
        self.var3 = '对象的公有属性'
        self.__var4 = '对象的私有属性__var4'
        var5 = '函数的局部变量'
        print var5
    def func2(self):
         print self.var1
         print self.__var2
    def func2(self):
        print self.var1
        print self.__var2
        print self.var3
        print self.__var4
        print var5
mc = MyClass()
mc.func1()
print "对象的内部属性"
print mc.__dict__
print "#"*50
print "类的内部属性"
print MyClass.__dict__
~                         
[root@133 class]# python test2.py 
函数的局部变量
对象的内部属性
{'_MyClass__var4': '\xe5\xaf\xb9\xe8\xb1\xa1\xe7\x9a\x84\xe7\xa7\x81\xe6\x9c\x89\xe5\xb1\x9e\xe6\x80\xa7__var4', 'var3': '\xe5\xaf\xb9\xe8\xb1\xa1\xe7\x9a\x84\xe5\x85\xac\xe6\x9c\x89\xe5\xb1\x9e\xe6\x80\xa7'}
##################################################
类的内部属性
{'func2': <function func2 at 0x7f95decde8c0>, '__module__': '__main__', 'var1': '\xe7\xb1\xbb\xe5\xb1\x9e\xe6\x80\xa7\xef\xbc\x8c\xe7\xb1\xbb\xe7\x9a\x84\xe5\x85\xac\xe6\x9c\x89\xe5\xb1\x9e\xe6\x80\xa7var1', '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, 'func1': <function func1 at 0x7f95decde7d0>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '_MyClass__var2': '\xe7\xb1\xbb\xe7\x9a\x84\xe7\xa7\x81\xe6\x9c\x89\xe5\xb1\x9e\xe6\x80\xa7__var2', '__doc__': None}6、类的方法总结
公有方法
私有方法
类方法
静态方法
内置方法
[root@133 class]# vim class_summary.py +32 #!/usr/bin/python #coding:utf8 class MyClass(object): name = 'Test' def func1(self): #公有方法可以在类的内部和外部被调用 print self.name, print "我是公有方法" self.__func2() def __func2(self): #私有方法只能在类的内部被调用 print self.name, print "我是私有方法" @classmethod #加类方法修饰器 def classFun(self): print self.name, print "我是类方法" @staticmethod #加静态方法修饰器,静态方法没有使用self def staticFun(): print MyClass.name, #通过类来引用name print "我是静态方法" mc = MyClass() #实例化静态方法 mc.func1() #对象调用公有方法,func1中调用了类的私有方法func2 mc.classFun() #对象调用类方法 mc.staticFun() #对象调用静态方法 MyClass.classFun() #类调用类方法 MyClass.staticFun() #类调用静态方法 [root@133 class]# python class_summary.py Test 我是公有方法 Test 我是私有方法 Test 我是类方法 Test 我是静态方法 Test 我是类方法 Test 我是静态方法 [root@133 class]# vim class_summary.py +32 #!/usr/bin/python #coding:utf8 class MyClass(object): name = 'Test' def __init__(self): #定义静态方法,初始化对象的时候就会执行 self.func1() self.__func2() self.classFun() self.staticFun() def func1(self): print self.name, print "我是公有方法" self.__func2() def __func2(self): print self.name, print "我是私有方法" @classmethod #加类方法修饰器 def classFun(self): print self.name, print "我是类方法" @staticmethod #加静态方法修饰器 def staticFun(): print MyClass.name, #通过类来引用name print "我是静态方法" mc = MyClass() #实例化对象的时候就会执行 [root@133 class]# python class_summary.py Test 我是公有方法 Test 我是私有方法 Test 我是私有方法 Test 我是类方法 Test 我是静态方法
上一篇: Python 爬虫 urllib模块:p
下一篇: Centos 7从python2.7.5
 51191
 50602
 41228
 38046
 32510
 29416
 28277
 23129
 23091
 21424
 1479°
 2194°
 1818°
 1748°
 2059°
 1810°
 2493°
 4183°
 4046°
 2889°