Python 面向对象编程OOP (二) slots,类的多态,继承,复写方法

__slots__魔法

你们好,上一期我重点总结了有关类的基本知识,如今简单回顾一下,顺便加上一个建立类时经常使用的东西:__slots__python

首先建立一个名人类:Celebritygit

class Celebrity:
     # 限定 Celebrity对象只能绑定name, age,domain属性,加速
    __slots__ = ['name','age',"domain"]
    # Class Attribute
    species = 'human'
    
    # Initializer / Instance Attributes
    def __init__(self, name, age, domain):
        self.name = name
        self.age = age
        self.domain = domain

能够发现用slots绑定了三个属性给Celebrity,slots的做用主要有两个:github

  • 若是须要限定自定义类型的对象只能绑定某些属性,能够经过在类中定义__slots__变量来进行限定。须要注意的是__slots__的限定只对当前类的对象生效,对子类并不起任何做用。
  • 加速

如今能够作个实验,首先咱们把slots绑定的domian属性去掉:app

class Celebrity:
    
    # Class Attribute
    species = 'human'
    __slots__ = ['name', 'age']
    # Initializer / Instance Attributes
    def __init__(self, name, age,domain):
        self.name = name
        self.age = age
        self.domain = domain
        
female_leader = Celebrity("Miss Dong",65,"electrical appliance")

# Access the instance attributes
print("{} is {}.".format(
    female_leader.name, female_leader.age))

Out:AttributeError: 'Celebrity' object has no attribute 'domain'

会发现报错了,即使咱们在init方法中有domain属性,可是因为slots中没有,因此Celebrity类下建立的实例都不能有domaindom

接下来让咱们简单回顾一下如何调用类变量:函数

female_leader = Celebrity("Miss Dong", 65,"electrical appliance")
male_leader = Celebrity("Jack Ma", 55,"internet")

# Access the instance attributes
print("{} is {} and {} is {}.".format(
    female_leader.name, female_leader.age, male_leader.name, male_leader.age))

# Is male_leader a human?
if male_leader.species == "human":
    print("{0} is a {1}!".format(male_leader.name, male_leader.species))  

Out:
Miss Dong is 65 and Jack Ma is 55.
Jack Ma is a human!

*args

其实args应该和 kargs一块儿来讲,可是今天先重点看一下它在对象中的应用,咱们如今给Celebrity类新建3个实例,而且咱们想知道年龄最大的是谁 ? code

这种状况下*args很好用:orm

a = Celebrity("Miss Dong",65,"electrical appliance")
b = Celebrity("Jack Ma", 55,"internet")
c = Celebrity("Lei Jun", 50,"mobile")

def get_oldest(*args):
    return max(args)

print("The big brother is {} years old.".format(get_oldest(a.age, b.age, c.age)))

Out:
The big brother is 65 years old.

固然,其余的应用场景还有不少,很少列举了对象

类的继承

首先,咱们在Celebrity类中新增两个方法:继承

  • description:对生成的大佬简单描述
  • speak: 大佬发言

完成后的结果以下:

class Celebrity:
     

    __slots__ = ['name', 'age',"domain"]
    species = 'human'

    def __init__(self, name, age, domain):
        self.name = name
        self.age = age
        self.domain = domain
        
     # instance method
    def description(self):
        return "{} is {} years old, working in the {} industry".format(self.name, self.age,self.domain)

    # instance method
    def speak(self, sound):
        return "{} says {}".format(self.name, sound)

如今新建两个类InternetBoss,MobileBoss,所有继承于Celebrity类:

# Child class (inherits from Dog() class)
    class InternetBoss(Celebrity):
        pass

    # Child class (inherits from Dog() class)
    class MobileBoss(Celebrity):
        pass

若是咱们什么都不作,会自动继承父类的 description和speak方法,作个实验,新建li做为InternetBoss的实例:

li = InternetBoss("Robbin",50,"advertisement")

调用description和speak方法:

li.description()
li.speak("What's your problem ?")

Out:
Robbin is 50 years old, working in the advertisement industry
Robbin says: What's your problem ?

再尝试一个MobileBoss的对象:

lei = MobileBoss("leijun", 50,"mobile")
lei.speak("Are you ok ?")

Out:
leijun says: Are you ok ?

能够发现都是同样的

类的多态, 复写父类的方法

对于类的多态,各类教程说的都太专业了,个人理解仅仅是:

  • 对父类现有方法A,当新增新的子类时,能够根据须要重写A。

在咱们如今的例子中,能够复写description方法:

class InternetBoss(Celebrity):
        def description(self):
            print("I'm Internet Boss !")
         
    class MobileBoss(Celebrity):
        def description(self):
            print("I'm Mobile phone Boss !")

这样InternetBoss类和MobileBoss类生成实例后,会调用本身的description方法:

li = InternetBoss("Robbin",50,"advertisement")
lei = MobileBoss("leijun", 50,"mobile")

li.description()
lei.description()

Out:
I'm Internet Boss !
I'm Mobile phone Boss !

isinstance() 和 issubclass()

Python 有两个判断继承的函数:

  • isinstance() 用于检查实例类型
  • issubclass() 用于检查类继承

如今还用咱们的例子说明一下,首先,这是咱们现有的三个类:

class Celebrity:
    __slots__ = ['name', 'age',"domain"]
    species = 'human'

    def __init__(self, name, age, domain):
        self.name = name
        self.age = age
        self.domain = domain
        
    def description(self):
        print( "{} is {} years old, working in the {} industry".format(self.name, self.age,self.domain))

    def speak(self, sound):
        print("{} says: {}".format(self.name, sound))
        
        
        
class InternetBoss(Celebrity):
    def description(self):
        print("I'm Internet Boss !")
         
class MobileBoss(Celebrity):
    def description(self):
        print("I'm Mobile phone Boss !")

而后咱们分别用不一样的类建立三个实例:

mingzhu = Celebrity("Miss Dong",65,"electrical appliance")
ma= InternetBoss("Pony", 48,"internet")
lei = MobileBoss("leijun", 50,"mobile")

如今使用issubclass()判断InternetBoss和MobileBoss是否继承自Celebrity:

# True
issubclass(InternetBoss,Celebrity) 

# True
issubclass(MobileBoss,Celebrity)

使用isinstance()查看mingzhu究竟是谁的实例:

# True
isinstance(mingzhu,Celebrity)

# False
isinstance(mingzhu,InternetBoss)

# False
isinstance(mingzhu,MobileBoss)

同理查看ma究竟是哪一个类的实例:

# True
isinstance(ma,Celebrity)

# True
isinstance(ma,InternetBoss)

# False
isinstance(ma,MobileBoss)

由于InternetBoss是Celebrity子类,因此ma同时是Celebrity和InternetBoss的实例。

若是咱们混用了issubclass和isinstance,会报错:

issubclass(ma,InternetBoss)

Out:
TypeError: issubclass() arg 1 must be a class

子类重写构造函数

刚才提到了,若是子类没有写构造函数init(),会自动继承父类的init,但咱们一般须要子类有不一样的初始函数,这样咱们就须要本身复写一下,这里以InternetBoss为例:

class InternetBoss(Celebrity):
    def __init__(self,name, age, domain,hometown):
        super().__init__(name, age, domain)
        self.hometown = hometown
        
    
    def description(self):
        print("I'm Internet Boss !")
        
    def __repr__(self):
        return f"This is {self.name} speaking !"

使用了super()会保留须要的父类初始化参数,再添加本身的就好了,这里的repr我会下次总结,如今再新建实例:

总结

此次我记录了slots用法,*args 的一个使用场景,类的继承,复写父类方法,构造函数等基本概念,剩下的慢慢来,我会一点点补充。。。

Ps: 本文的实例名称均为杜撰,请不要对号入座...

个人其余文章已经放到了Github上,若是感兴趣的朋友能够去看看,连接以下:

相关文章
相关标签/搜索