class是一个关键字,告诉系统我们要定义一个类, class后面加一个空格然后加类名。
类名规则:首字母大写,如果多个单词用驼峰命名法,比如:KingMao
类名后面的小括号里是本类基于某个类(父类)定义,属于继承相关知识,暂不深入。
class Dog:
def eat(self,eat):
print(f'本汪吃了{eat}个苹果')
def bark(self,bark_1,bark_2):
return bark_1,bark_2
hary = Dog()
print(hary, type(hary))
hary.eat(4)
bark_total = hary.bark(3,6)
print(bark_total)
xiaoquan = Dog()
print(xiaoquan, type(xiaoquan))
xiaoquan.eat(3)
hary.name = 'anbei'
print(hary.name)
本汪吃了4个苹果
(3, 6)
<main.Dog object at 0x000001CC43933DC0> <class 'main.Dog'>
本汪吃了3个苹果
anbei
class Pig(object):
def __init__(self, name, age):
self.name = name
self.age = age
def add_pig(self, a, b):
return a + b
def show(self):
print(self.name, self.age)
sanpang = Pig('sanpang', 19)
pig_total = sanpang.add_pig(4, 7)
print(pig_total)
print(sanpang.name, sanpang.age)
sanpang.age = 80
print(sanpang.age)
sanpang.show()
11
sanpang 19
80
sanpang 80