今天学习了有关“类”的操作



# 创建和使用类
class Dog():
    # 首字母大写代表类
    def __init__(self, name, age):
        # 命名方法旨在避免Python默认方法与普通方法的名称冲突
        self.name = name
        self.age = age
        self.type = 'Samoye'  # 给属性默认值

    def sit(self):
        print(self.name.title() + "is now sitting.")

    def roll_over(self):
        print(self.name.title() + " rolled over!")

    def update_type(self, new_type):
        self.type = new_type

    def update_age(self, new_age):
        # 禁止对年龄的回溯
        if new_age >= self.age:
            self.age = new_age
        else:
            print("You can't roll back the age")

    def increment_age(self, add_age):
        # 通过方法对属性的值进行递增
        self.age += add_age

# 创建实例
my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
print(my_dog.type)
my_dog.sit()
my_dog.roll_over()
# 直接修改属性值
my_dog.type = 'Hashiqi'
print(my_dog.type)
# 通过方法修改属性的值
my_dog.update_type('Chaiquan')
print(my_dog.type)
# 通过方法对属性的值进行递增
my_dog.increment_age(5)
print(my_dog.age)

# 子类对父类的继承
class Cat(Dog):
    def __init__(self, name, age):
        super().__init__(name, age)
        # 帮助父类和子类联系起来,父类又称superclass
        self.color = 'white'
        # 额外定义子类的属性

    def describe_color(self):
        print("This cat's color is " + self.color)

    # 重写父类
    def sit(self):
        print(self.name.title() + " can't be sitting.")

my_cat = Cat('Tesla', 2)
print(my_cat.name)
my_cat.describe_color()
my_cat.sit()

""""引用模块中类的方法和引用函数类似,但应注意,使用该模块的程序都必须使用更具体的文件名"""

整体输出结果如下:

My dog's name is Willie.
My dog is 6 years old.
Samoye
Willieis now sitting.
Willie rolled over!
Hashiqi
Chaiquan
11
Tesla
This cat's color is white
Tesla can't be sitting.


玄枵
1 声望0 粉丝

正在努力学习Python