Skip to content

概念

类是面向对象编程中经常使用的一个概念,根据类来创建对象被称为实例化。

python
class Dog:
    # 类中的函数称为方法,每当你根据Dog类创建新实例时,Python就会自动运行__init__
    def __init__(self, name, age):
        """初始化属性name和age"""
        self.name = name
        self.age = age

    def sit(self):
        """模拟小狗被命令蹲下"""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """模拟小狗被命令时打滚"""
        print(self.name.title() + " rolled over!")


my_dog = Dog("willie", 6)  # 根据类创建实例
print(my_dog.name)
my_dog.sit()

继承

python
class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()


class ElectricCar(Car):
    """电动汽车的独特之处"""
    def __init__(self, make, model, year):
        """初始化父类的属性"""
        super().__init__(make, model, year)

从外部文件导入类

同函数的导入