class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
self.weight = 10
self.height = 0
def sit(self):
print(self.name + " is sitting.")
def sleep(self):
print(self.name + " is sleeping.")
def read_weight(self): # def weight:函数名/变量名重用 is not callable
print("the weight:", self.weight) # 不转str也可
def read_height(self, new_value):
self.height = new_value
print("the height:", self.height)
def read_age(self):
self.age = self.age + 1
print("the new age:", self.age)
# create instance #
dog_a = Dog('Hello', 3)
dog_a.sit()
dog_a.read_weight()
# update attribute #
dog_a.weight = 20
dog_a.read_weight() # change directly
dog_a.read_height(30) # change vio method
# increment attribute's value #
dog_a.read_age()
# Inheritance #
class BorderCollie(Dog):
def __init__(self, name, age):
super().__init__(name, age) # super(): the connection between SuperClass and SubClass
self.size = 30
def read_size(self):
print("the size:", self.size)
def sleep(self):
print(self.name + " is not sleeping.")
BorderCollie_1 = BorderCollie("World", 5)
BorderCollie_1.sit()
BorderCollie_1.read_size()
# override #
BorderCollie_1.sleep()
[Python Crash Course] Basics_Class
最新推荐文章于 2020-11-27 04:42:16 发布