初识对象
程序中数据的组织
class Student:
name = None # 记录学生姓名
# 基于类创建对象
stu_1 = Student()
stu_2 = Student()
# 对象属性赋值
stu_1.name = '周杰轮'
stu_2.name = '林军杰'
成员方法
class Student:
name = None
age = None
def say_hi(self):
print(f"Hi大家好,我是{self.name}")
stu = Student()
stu.name = "周杰轮"
stu.say_hi()
self关键字注意事项
class Student:
name = None
def say_hi(self):
print("Hello")
def say_hi2(self, msg):
print(f"Hello {msg}")
stu = Student()
stu.say_hi() # 无需传参
stu.say_hi2("你好") # 需要参数
类和对象

类如同设计图纸,对象是基于图纸生产的实体
构造方法
class Student:
def __init__(self, name, age, tel):
self.name = name
self.age = age
self.tel = tel
print("Student类创建了一个对象")
stu = Student("周杰轮", 31, "18500006666")
内置方法
字符串方法 __str__
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Student类对象, name={self.name}, age={self.age}"
student = Student("周杰轮", 11)
print(student) # 输出格式化字符串
比较方法 __lt__
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __lt__(self, other):
return self.age < other.age
stu1 = Student("周杰轮", 11)
stu2 = Student("林军杰", 13)
print(stu1 < stu2) # 输出: True
封装与继承
class Phone:
__current_voltage = 0.5 # 私有变量
def __keep_single_core(self): # 私有方法
print("省电模式")
def call_by_5g(self):
if self.__current_voltage >= 1:
print("5G通话")
else:
self.__keep_single_core()
# 多继承示例
class MyPhone(Phone, NFCReader, RemoteControl):
pass
类型注解
from typing import Union
# 容器类型注解
my_list: list[Union[str, int]] = [1, 2, 'itheima']
def func(data: Union[int, str]) -> Union[int, str]:
pass
多态示例
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("汪汪汪")
class Cat(Animal):
def speak(self):
print("喵喵喵")
def make_noise(animal: Animal):
animal.speak()
make_noise(Dog()) # 输出: 汪汪汪
make_noise(Cat()) # 输出: 喵喵喵
评论(已关闭)
评论已关闭