详解Python类与对象(下)

前言

上节课我们介绍了Python面向对象的基本概念和使用,本节课将继续讲解Python面向对象,主要分为两个部分,第一个是继承,第二个是私有化。

希望这两次分享能让初学者能够基本了解Python面向对象编程,并按实际需求编写出自己定义的类。

继承

继承是每个人的梦想。

继承的写法很简单,只需要在定义子类时,指定父类即可。

class Animal:

    leg = 4

    def __init__(self, species, furcolor):
        self.species = species
        self.furcolor = furcolor

    def call(self):
        return '{} is calling'.format(self.species)


class Dog(Animal):

    def __init__(self, species, furcolor, name):
        super().__init__(species, furcolor)
        self.name = name

    def get_name(self):
        print(self.name)


dog1 = Dog('dog', 'red', 'lucky')
print(dog1.call())
print(dog1.leg)
dog1.get_name()

dog is calling
4
lucky

继承其实比较好理解的,子类可以调用父类的属性和方法,如果子类重新进行了定义(我们通常叫重写),那就会使用子类的属性。

论私有化

在正式聊私有化之前,我希望你记住一句话,Python的私有化不是真正意义上的私有化。

默认情况下,我们是可以直接发问对象的属性和方法的,如下所示。

class Animal:

    leg = 4

    def __init__(self, species, furcolor):
        self.species = species
        self.furcolor = furcolor

    def call(self):
        return '{} is calling'.format(self.species)


dog = Animal('dog', 'gray')
print(dog.species)

dog

但有人觉得这样做破坏了封装的原则,我认为主要原因有两个。

第一目的是为了让程序员直接调用接口(可能是部分方法),而不用去关心具体内容,因为对他们而言,调用这些属性和方法没有意义。

第二个目的是在继承时的考虑,如果子类和父类具有同样的属性,那子类必定会覆盖属性,,定义了私有属性可以防止这样的事情发生。

那怎么让属性私有化了?其实很简单,我们用双下划线开始定义属性即可。

class Animal:

    leg = 4

    def __init__(self, species, furcolor):
        self.__species = species
        self.furcolor = furcolor

    def call(self):
        return '{} is calling'.format(self.species)


dog = Animal('dog', 'gray')
print(dog.species)

Traceback (most recent call last):
  File "/Users/luopan/Python练习/Python基础语法/类与对象.py", line 136, in <module>
    print(dog.species)
AttributeError: 'Animal' object has no attribute 'species'

还记得我之前说的那句话吗,真的不能调用了吗?我们来看看实例的dict属性。

class Animal:

    leg = 4

    def __init__(self, species, furcolor):
        self.__species = species
        self.furcolor = furcolor

    def call(self):
        return '{} is calling'.format(self.species)


dog = Animal('dog', 'gray')
print(dog.__dict__)

{'_Animal__species': 'dog', 'furcolor': 'gray'}

我们发现其实私有属性改为了_Animal__species,所以调用它,也是可以反问私有属性的。

dog = Animal('dog', 'gray')
print(dog._Animal__species)

dog

所以,有人不太赞同这种写法,并使用单下划线来代替,易于理解,定下这个规定,程序员也不在类外部访问这种属性。

总结

今天的分享就到这了,但Python类与对象的并不止这些,接下来我会慢慢分享给大家,希望大家持续关注罗罗攀,我们下期再见~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章