明天学习了无关“类”的操作
# 创立和应用类
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.