Python中类的内置方法与继承关系实例
admin
2023-07-07 03:42:42
0

1.类的内置方法

Python内部类:
所谓内部类,就是在类的内部定义的类,主要目的是为了更好的抽象现实世界。
例子:
汽车是一个类,汽车的底盘轮胎也可以抽象为类,将其定义到汽车内中,而形成内部类,
更好的描述汽车类,因为底盘轮胎是汽车的一部分。

内部类实例化方法:

方法1:直接使用外部类调用内部类
方法2:先对外部类进行实例化,然后再实例化内部类

out_name = outclass_name()
in_name = out_name.inclass_name()
in_name.method()
#!/usr/bin/env python
#-*- coding:utf-8  -*-
class People(object):
    color = 'yellow'
    __age = 30   #私有属性

    class Chinese(object):
        print("I am chinese")

    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 with Tom"

    @classmethod #调用类的方法 
    def test(self):
        print ("this is class method")

    @staticmethod  #调用类的方法 
    def test1():    
        print ("this is static method")

jack = People.Chinese()
#!/usr/bin/env python
#-*- coding:utf-8  -*-
class People(object):
    color = 'yellow'
    __age = 30   #私有属性

    class Chinese(object):
        name ="I am a Chinese."

    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 with Tom"

    @classmethod #调用类的方法 
    def test(self):
        print ("this is class method")

    @staticmethod  #调用类的方法 
    def test1():    
        print ("this is static method")

jack = People.Chinese()  #外部类调用内部类
print jack.name     #外部类调用内部类对象
另一种方法,外部类调用内部类对象
#!/usr/bin/env python
#-*- coding:utf-8  -*-
class People(object):
    color = 'yellow'
    __age = 30   #私有属性

    class Chinese(object):
        name ="I am a Chinese."

    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 with Tom"

    @classmethod #调用类的方法 
    def test(self):
        print ("this is class method")

    @staticmethod  #调用类的方法 
    def test1():    
        print ("this is static method")

ren = People()            #实例化外部类
jack = ren.Chinese()   #实例化内部类
print jack.name           #打印内部类属性

或
print People.Chinese.name
print People.Chinese().name
魔术方法:

str(self)
构造函数与析构函数
构造函数:

用于初始化类的内部状态,Python提供的构造函数是__init__():
__init__():方法是可选的,如果不提供,python会给出一个默认的__init__方法。

析构函数:

用于释放对象占用的资源,python提供的析构函数是__del__():
__del__():也是可选的,如果不提供,则python会在后台提供默认析构函数。

构造函数str

#!/usr/bin/env python
#-*- coding:utf-8  -*-
class People(object):
    color = 'yellow'
    __age = 30   #私有属性

    class Chinese(object):
        name ="I am a Chinese."

    def __str__(self):
        return "This is People class"

    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 with Tom"

    @classmethod #调用类的方法 
    def test(self):
        print ("this is class method")

    @staticmethod  #调用类的方法 
    def test1():    
        print ("this is static method")

ren = People()            #实例化外部类
print ren     #默认执行__str__
__init__(self)初始化类:
#!/usr/bin/env python
#-*- coding:utf-8  -*-
class People(object):
    color = 'yellow'
    __age = 30   #私有属性

    class Chinese(object):
        name ="I am a Chinese."

    def __str__(self):
        return "This is People class"

    def __init__(self,c='white'):   #类实例化时自动执行
        self.color = c
 self.think()

    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 with Tom"

    @classmethod #调用类的方法 
    def test(self):
        print ("this is class method")

    @staticmethod  #调用类的方法 
    def test1():    
        print ("this is static method")

jack = People('green')
ren = People()            #实例化外部类
print ren.color        #通过对象访问属性是初始化后的值
print People.color    #通过类访问还是原来的值   

[root@localhost 20180110]# python test1.py 
I am a black 
I am a thinker
30
black
yellow
析构函数__del__():释放资源

#!/usr/bin/env python
#-*- coding:utf-8  -*-
class People(object):
    color = 'yellow'
    __age = 30   #私有属性

    class Chinese(object):
        name ="I am a Chinese."

    def __str__(self):
        return "This is People class"

    def __init__(self,c='white'):   #类实例化时自动执行
        print ("initing...")
 self.color = c
        self.think()
        f = open('test.py')

    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 with Tom"

    @classmethod #调用类的方法 
    def test(self):
        print ("this is class method")

    @staticmethod  #调用类的方法 
    def test1():    
        print ("this is static method")

     def __del__(self):
          print ("del....")
   self.f.close()

jack = People('green')
ren = People()            #实例化外部类
print ren.color        #通过对象访问属性是初始化后的值
print People.color    #通过类访问还是原来的值   
垃圾回收机制:

Python采用垃圾回收机制来清理不再使用的对象;python提供gc模块释放不再使用的对象。
Python采用“引用计数”的算法方式来处理回收,即:当然某个对象在其作用域内不再被其
他对象引用的时候,python就自动化清除对象。
gc模块collect()可以一次性收集所有待处理的对象(gc.collect)

#!/usr/bin/env python
#-*- coding:utf-8  -*-
class People(object):
    color = 'yellow'
    __age = 30   #私有属性

    class Chinese(object):
        name ="I am a Chinese."

    def __str__(self):
        return "This is People class"

    def __init__(self,c='white'):   #类实例化时自动执行
        print ("initing...")
                 self.color = c
        self.think()
        f = open('test.py')

    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 with Tom"

    @classmethod #调用类的方法 
    def test(self):
        print ("this is class method")

    @staticmethod  #调用类的方法 
    def test1():    
        print ("this is static method")

     def __del__(self):
          print ("del....")
   self.f.close()

print gc.collect()     如果是0是没有回收的。
jack = People('green')
ren = People()            #实例化外部类
print ren.color        #通过对象访问属性是初始化后的值
print People.color    #通过类访问还是原来的值   

2.类的继承

类的继承

继承是面向对象的重要特性之一,

继承关系继承是相对两个类而言的父子关系

子类继承了父类的所有公有属性和方法,

继承,实现了代码重用

使用继承

继承可以重用已经存在的数据和行为,减少代码的重复编写,

Python在类名后使用一对括号来表示继承关系,括号中的即类为父类

class Myclass(ParentClass),

如果父类定义了__init__方法,子类必须显式调用父类的__init__方法,

ParentClass.__init__(self,[args...])

如果子类需要扩展父类的行为,可以添加__init__方法的参数.

#!/usr/bin/env python

#-*- coding:utf-8  -*-

class People(object):

    color = 'yellow'

    def think(self):

    self.color = "black"

    print "I am a %s "  % self.color

    print ("I am a thinker")

class Chinese(People):

    pass

cn = Chinese()

print cn.color

cn.think()
父类中有构造函数:

#!/usr/bin/env python

#-*- coding:utf-8  -*-

class People(object):

    color = 'yellow'

     def __init__(self):

        print "Init..."

        self.dwell = 'Earth'

    def think(self):

        print "I am a %s "  % self.color

        print ("I am a thinker")

class Chinese(People):

    pass

cn = Chinese()

print cn.dwell

cn.think()

参数大于两个:
Super 函数

#!/usr/bin/env python

#-*- coding:utf-8  -*-

class People(object):

    color = 'yellow'

    def __init__(self,c):

        print "Init..."

        self.dwell = 'Earth'

     def think(self):

        print "I am a %s "  % self.color

        print ("I am a thinker")

class Chinese(People):

     def __init__(self):

        People.__init__(self,'red')

        pass

cn = Chinese()

class A(object):

        def __init__(self):

            print "enter A"

            print "leave A"

class B(object):

        def __init__(self):

            print "enter B"

            super(B,self),__init__()

            print "leave B"

b = B()

#!/usr/bin/env python

#-*- coding:utf-8  -*-

class People(object):

    color = 'yellow'

    def __init__(self,c):

        print "Init..."

        self.dwell = 'Earth'

    def think(self):

        print "I am a %s "  % self.color

        print ("I am a thinker")

class Chinese(People):

    def __init__(self):

       super(Chinese,self).__init__('red')

       pass

cn = Chinese()

cn.think()

#!/usr/bin/env python

#-*- coding:utf-8  -*-

class People(object):

    color = 'yellow'

    def __init__(self,c):

        print "Init..."

        self.dwell = 'Earth'

    def think(self):

        print "I am a %s "  % self.color

        print ("I am a thinker")

class Chinese(People):

    def __init__(self):

        super(Chinese,self).__init__('red')

     def talk(self):

        print "I like taking."

cn = Chinese()

cn.think()

cn.talk()

多重继承

Python支持多重继承,第一个类可以继承多个父类

语法:

class class_name(Parent_c1,Parent_c2,...)

注意:

当父类中出现多个自定义的__init__的方法时,

多重继承,只执行第一个累的__init_方法,其他不执行。
#!/usr/bin/env python

#-*- coding:utf-8  -*-

class People(object):

    color = 'yellow'

    def __init__(self):

        print "Init..."

        self.dwell = 'Earth'

    def think(self):

        print "I am a %s "  % self.color

        print ("My home is %s ") % self.dwell

class Martian(object):

    color = 'red'

    def __init__(self):

        self.dwell = 'Martian'

class Chinese(People,Martian):

    def __init__(self):

        People.__init__(self)

cn = Chinese()

cn.think()
#!/usr/bin/env python

#-*- coding:utf-8  -*-

class People(object):

    def __init__(self):

        self.dwell = 'Earth'

         self.color = 'yellow'

    def think(self):

        print "I am a %s "  % self.color

        print ("My home is %s ") % self.dwell

class Martian(object):

    color = 'red'

    def __init__(self):

        self.dwell = 'Martian'

    def talk(self):

        print "I like talking"

class Chinese(Martian,People):

    def __init__(self):

        People.__init__(self)

cn = Chinese()

cn.think()

cn.talk()

相关内容

热门资讯

我国科学家为细胞信号“导航”开... 新华社济南5月31日电(记者张力元)人体细胞犹如一座精密的通信城市,每天都有大量“指令”穿梭传递,调...
极端大风突袭哈尔滨!过山车停摆... 极目新闻记者 詹钘5月31日,受强对流天气影响,哈尔滨国际会展中心体育场相关设施受到损坏,原计划当晚...
三原电缆取得电缆接头连接用防护... 国家知识产权局信息显示,上海三原电缆附件有限公司取得一项名为“一种电缆接头连接用防护结构”的专利,授...
原创 识... 还是那句话,机圈苦大屏久已…… 虽然大屏有大屏的美,但是小屏也有小屏的俏。在大屏旗舰占据主流的手机市...
玄戒技术取得分频电路专利,实现... 国家知识产权局信息显示,北京玄戒技术有限公司取得一项名为“分频电路、分频器、射频芯片和电子设备”的专...
为什么今年香会基调明显变了 5月29日—31日在新加坡举行的第23届香格里拉对话会(简称“香会”),见证着元首引领下大国关系继续...
成本几毛钱、假驱蚊液香精兑水,... 入夏升温,蚊虫进入活跃期,驱蚊防护成为民生刚需,《财经调查》持续接到消费者投诉,他们买到的多款网红驱...
越来越多80后90后,正在丧失... 六一儿童节到来之际,朋友圈里开始出现一种熟悉的热闹。有人晒出零食礼包,有人半开玩笑地向伴侣讨礼物,还...
洋保电子取得用于低温环境的电气... 国家知识产权局信息显示,洋保电子(太仓)有限公司取得一项名为“一种用于低温环境的电气柜”的专利,授权...
中日韩飞手争霸宁波!2026无... 潮新闻客户端 记者 陈冲 通讯员 朱凝 5月31日,2026小遛·无人机竞速世界杯(中国·宁波鄞州站...