python

xiaoxiao2021-02-28  106

def 函数名(): xxxx

定义一个类的方式为: class 类名: xxxxx

#定义一个猫类 class Cat: #属性 #方法 def eat(self): print('%s吃%s'%("-"*5,'-'*5)) def play(self): print('-----玩-----') xiaohuamao = Cat().eat() #打印结果-----吃-----

获取对象属性

#定义一个猫类 class Cat: #属性 #方法 def eat(self): print('%s吃%s'%("-"*5,'-'*5)) def play(self): print('-----玩-----') #定义一个获取对象属性的方法 def printattrs(self): #这个self有点像this 表示这个对象的属性,当在下面定义color,方法中就可以使用 print(self.color) xiaohuamao = Cat() #给小花猫对象添加属性 xiaohuamao.color = '红色' #获取小花猫的属性 a = xiaohuamao.color print(a)#打印红色 xiaohuamao.printattrs()#打印红色

综合上面的代码的出来的结论 给一个对象添加属性方法为: 对象名.新的属性名 = 值

获取这个对象的属性,2种方法: 1. 对象.属性 2. 定义一个方法,这个方法中,使用 self.属性

初始化类init(self)

#定义一个猫类 class Cat: #属性 #初始化 def __init__(self,color): print(color,"初始化") Cat('红色')#打印出来的结果是红色 初始化 #定义一个猫类 class Cat: #属性 #初始化 def __init__(self,newcolor): #这个对象color属性赋值 self.color=newcolor print(newcolor,"初始化") #方法 def eat(self): print('%s吃%s'%("-"*5,'-'*5)) def play(self): print('-----玩-----') #定义一个获取对象属性的方法 def printattrs(self): # print(self.color) #这样生成的是这个类的属性,当对象调用时,因为代码块最先生成,可以声明这个对象的属性 xiaohuamao = Cat("红色") xiaohuamao.printattrs()#打印结果红色

init()方法 1. 是python自动调用的方法,调用的时间为:创建完对象之后,立马自动调用 2. 不需要开发者调用,即 对象名.init() 3. 这个方法一般情况下会完成一些默认的事情,比如添加一些属性

class Xxxx: def __init__(self, new_a, new_b): self.a = new_a self.b = new_b 注意:new_a、new_b 是局部变量,并不是对象的属性,如果想在__init__方法中添加属性的话,需要使用类似 self.属性名 = 值 的格式,此时self.a = new_a表示的是给对象添加一个属性,这个属性名为a,这个属性的值为局部变量new_a里面的值

_ str _

#定义一个猫类 class Cat: def __init__(self,newcolor): self.color = newcolor #让对象接受返回值 def __str__(self): return self.color wangcai = Cat('黑') #如果没有str返回应该是内存地址,用了str方法打印结果黑 print (wangcai)

面向对象烤地瓜

class sweetPotato: def __init__(self): #属性初始化赋值 self.cookedaLevel = 0 self.cookedString = '生的' self.condiments = [] #烤的时间 def cook(self,times): self.cookedaLevel += times if self.cookedaLevel > 8: self.cookedString = '木炭' elif self.cookedaLevel > 5: self.cookedString = "烤好了" elif self.cookedaLevel > 3: self.cookedString = '半生不熟' else: self.cookedString = '生的' #添加作料 def addCondiments(self,temp): self.condiments.append(temp) #对象返回值 def __str__(self): str_cond='' for temp in self.condiments: str_cond +=temp+',' #用切片去逗号 return '地瓜的生熟度'+self.cookedString+'等级'+str(self.cookedaLevel)+str_cond[:-1] print('准备烤地瓜了') diGua = sweetPotato() diGua.cook(1) diGua.addCondiments("芥末") diGua.addCondiments("芥末") diGua.addCondiments("芥末") print(diGua)
转载请注明原文地址: https://www.6miu.com/read-44093.html

最新回复(0)