Python日常笔记(15) - 面向对象

面向对象

类,属性,方法,对象体验

# 类,属性,方法,对象体验
class Student:
   no = 0
   name = ""
   age = 0
   def print(self, no, name, age):
       self.no = no
       self.name = name
       self.age = age
       print(f"学号:{self.no},姓名:{self.name}年龄:{self.age}")
# 创建对象
student = Student()
# 调用方法
student.print(1, "张三", 20)

构造方法__init__

构造方法是自动调用的

class Student:
   no = 0
   name = ""
   age = 0
   # 构造方法
   def __init__(self, no, name, age):
       self.no = no
       self.name = name
       self.age = age
   # 打印方法
   def print_info(self):
       print(f"学号:{self.no},姓名:{self.name}年龄:{self.age}")
# 创建对象
student = Student(1, "张三", 20)
# 调用方法
student.print_info()

魔幻方法_str_

这个方法类似java中的重写tostring方法

class Student:
   def __str__(self):
       return "类似重写java中的tostring方法"
# 创建对象
student = Student()
print(student)


__del__方法是被系统自动调用

类和对象练习

# 类和对象练习
class SweetPotato:

   # 构造方法
   def __init__(self):
       self.countTime = 0
       self.status = "生的"
       self.condiments = []

   # 业务方法
   def cook(self, time):
       self.countTime += time
       if 0 <= self.countTime < 3:
           self.status = "生的"
       elif 3 <= self.countTime < 5:
           self.status = "半生不熟"
       elif 5 <= self.countTime < 8:
           self.status = "熟了"
       elif self.countTime >= 8:
           self.status = "糊了"

   # 业务方法
   def condiment_info(self, condiment):
       self.condiments.append(condiment)

   # tostring方法
   def __str__(self):
       return f"时间为:{self.countTime}分钟,状态为:{self.status},调料为:{self.condiments}"
# 创建对象
sweetPotato = SweetPotato()
sweetPotato.cook(2)
sweetPotato.condiment_info("酱油")
print(sweetPotato)
sweetPotato.cook(2)
sweetPotato.condiment_info("味精")
print(sweetPotato)
sweetPotato.cook(2)
sweetPotato.condiment_info("食盐")
print(sweetPotato)
sweetPotato.cook(2)
print(sweetPotato)

作者:阿超
原创公众号:『Python日常笔记』,专注于 Python爬虫等技术栈和有益的程序人生,会将一些平时的日常笔记都慢慢整理起来,也期待你的关注和阿超一起学习,公众号回复【csdn】优质资源。

发布了55 篇原创文章 · 获赞 16 · 访问量 9510

猜你喜欢

转载自blog.csdn.net/duchaochen/article/details/105052753
今日推荐