1、创建类和对象,并调用对象数据的方式。
1 #定义一个类 2 class Cat: 3 #类的方法 4 def eat(self): 5 print('吃') 6 def drink(self): 7 print('喝') 8 #通过方法访问对象的属性 9 def printInfo(self): 10 print(self.weiba) 11 #创建一个对象 12 a1=Cat() 13 a1.eat() 14 a1.drink() 15 #给对象添加属性 16 a1.weight='5kga' 17 a1.weiba='有' 18 #1调用对象的属性获取数据 19 a2=a1.weight 20 #a3=a1.weiba 21 print(a2) 22 #print(a3) 23 #2通过函数调用对象的数据 24 a1.printInfo() ~运行结果
吃 喝 5kga 有
2、init方法-初始化方法;在方法中添加属性
1 #定义一个类 2 class Cat: 8 #通过方法访问对象的属性 9 def printInfo(self): 10 print(self.weiba) 11 #__init__函数,创建对象后,会立马使用 12 def __init__(self,newcolor,newweight,newweiba): 13 #在方法中添加属性 14 self.color=newcolor 15 self.weight=newweight 16 self.weiba=newweiba 17 print('hahaha') 18 #创建一个对象 19 a1=Cat('白','5','有') 32 a1.printInfo()
运行结果
hahaha
有