
01
引言
大家首先需要记住一句话:类是模板,而实例则是根据类创建的对象。在面向对象编程语言中,类class最为常见。为此,本文重点来介绍在Python中创建类的六重境界。
02
Level1:Basic class
class Dog:passdog = Dog() # initializing
03
Level 2:Basic class with basic method
我们这里不再直接使用关键字pass,在类内什么都不做。因此,我们可以考虑通过添加相应的成员函数来实现相应的功能。
class Dog:def bark(self):print("woof")dog = Dog()dog.bark() # woof
04
Level 3:使用 __init__ 函数
接着让我们在类内添加一个__init__魔法方法,首先需要理解的是,两个下划线开头的函数是声明该属性为类内私有函数,同时__init__函数支持带参数类的初始化,也可同时声明该类的属性(类内成员变量)。
class Dog:def __init__(self, name, age):self.name = nameself.age = agedef bark(self):print("woof)dog1 = Dog("rocky", 4) # name="rocky" age=4dog2 = Dog("lucky", 5) # name="lucky" age=5
05
Level 4: 从父类继承
通过使用类Dog(Animal)语法,我们可以使Dog类继承父类Animal类。这意味着Dog类可以访问父类Animal类中的任何属性或方法。
class Animal:def speak(self):print("hello")class Dog(Animal):passdog = Dog()dog.speak() # hello
06
Level 5: 从其他类继承__init__函数
如果我们的子类与父类有不同的__init__函数,此时我们可以在子类中使用super().__init__。这实际上是在子类中的__init__函数中调用父类中的__init__函数。
class Rectangle:def __init__(self, length, width):self.length = lengthself.width = widthdef area(self):return self.length * self.widthclass Square(Rectangle):def __init__(self, length):super().__init__(length, length) # Rectangle's __init__
上述代码中,在类Square的__init__函数中,我们使用super().__init__函数,本质上是调用父类Rectangle中的__init__函数。由于正方形中的长度等于宽度,所以这里我们将length传递给super().__init__两次。
r = Rectangle(5, 4)r.area() # 20s = Square(3)s.area() # 9
07
什么?你说在定义类的时候经常忘记写函数__init__,此时我们不妨来使用dataclass。
from dataclasses import dataclassclass Dog:name: strage: intdef bark(self):print(f"woof name={self.name} age={self.age}")dog = Dog("rocky", 4)dog.bark() # woof name=rocky age=4
08
总结
您学废了嘛?
点击上方小卡片关注我
万水千山总关情,点个在看行不行。

