类与对象 & 类型注解
1. 初识对象
Class可以当作一个字典来用!
2. 类的成员方法
self表示类对象本身,并且只有通过self,成员方法才能访问类的成员变量/其他成员方法!
如果是由外部传入的参数,则不需要加self!
3. 类和对象
4. 构造方法__init__
练习:
class Student: def __init__(self, name, age, address): self.name = name self.age = age self.address = address for i in range(1, 11): print("当前录入第%d位学生信息, 总共需录入10位学生信息" % i) name = input("请输入学生姓名:") age = int(input("请输入学生年龄:")) address = input("请输入学生地址:") locals()[f"stu{i}"] = Student(name, age, address) print(f"学生{i}信息录入完成," f"信息为【学生姓名:{locals()[f'stu{i}'].name}," f"年龄:{locals()[f'stu{i}'].age}," f"地址:{locals()[f'stu{i}'].address}】")
⭐一个小技巧:可以通过locals()[字符串]将字符串转变为变量名!
5. 魔术方法
6. 封装
私有成员变量和私有成员方法:(不能被类对象直接使用!)
练习:
class Phone: __is_5g_enable = False def __check_5g(self): if self.__is_5g_enable: print("5g开启") else: print("5g关闭,使用4g网络") def call_by_5g(self): self.__check_5g() print("正在通话中") phone = Phone() phone.call_by_5g()
7. 继承
继承:拿来吧你!
多继承从左到右依次继承!
因此,当有同名的成员变量或成员方法时,会使用优先级高的父类的成员变量或成员方法!
复写和调用父类成员:
8. 类型注解
A. 变量的类型注解
var1: int = 6 var2: float = 3.14 var3: bool = True class Student: pass stu: Student = Student() # 使用注释进行注解 var1 = 6 # type: int var2 = 3.14 # type: float var3 = True # type: bool # 简单注解 my_str: str = "hello" my_lst: list = [1, 2, 3] my_tup: tuple = (6, "hello", True) my_set: set = {1, 2, 3} my_dict: dict = {"hello": 6} # 详细注解 my_str: str = "hello" my_lst: list[int] = [1, 2, 3] my_tup: tuple[int, str, bool] = (6, "hello", True) # 注意:元组需要对每一个元素进行注解 my_set: set[int] = {1, 2, 3} my_dict: dict[str, int] = {"hello": 6}
B. 函数和方法的类型注解
def add(x: list[int]) -> int: return int(sum(x)) print(add([1, 2, 3]))
C. Union类型
from typing import Union my_lst: list[Union[int, str]] = [1, 2, "itheima", "itcast"] my_dict: dict[str, Union[str, int]] = {"hello": "hi", "what": 1} def func(data: Union[int, str]) -> Union[int, str]: pass func() # Ctrl + P 查看参数和参数类型
9. 多态
面向对象编程的三大特征:封装、继承、多态!