类和对象
# 使用对象组织数据
# 设计一个类
import random
class Student:
name = None
gender = None
age = None
# 创建一个对象
stu_1 = Student()
# 对象属性赋值
stu_1.name = "詹姆斯"
stu_1.gender = "男"
stu_1.age = 39
# 类的成员方法
class Person:
name = None
def sayHi(self): # self必须要有,代表这个对象本身
print(f"Hello,I am {self.name}")
def sayHi2(self, msg):
print(f"Hello,I am {self.name}, {msg}")
person = Person()
person.name = "Curry"
person.sayHi() #self在调用的时候不用传入
person.sayHi2("666")
# 类和对象
class Clock:
id = None
price = None
def ring(self):
import winsound
winsound.Beep(2000,3000) # 频率,持续时间
c1 = Clock()
c1.id = "001"
c1.price = 19.99
print(f"c1.price is {c1.price}")
c1.ring()
# 构造方法
class Man:
name = None
age = None
tel = None
# 构造方法名称
def __init__(self, name, age, tel):
self.name = name
self.age = age
self.tel = tel
print("Man创建了一个对象")
man = Man("Kobe", 4, "4234234243")
# 魔术方法:python类的内置方法 前后均有两个下划线
class Woman:
name = None
age = None
def __init__(self, name, age):
self.name = name
self.age = age
# __str__:返回字符串
def __str__(self):
return f"{self.name}, {self.age}"
# __lt__:定义两个对象的比较逻辑,只用于小于大于
def __lt__(self, other):
return self.age < other.age
# __le__:小于等于和大于等于的判断
def __le__(self, other):
return self.age <= other.age
# __eq__:判等
def __eq__(self, other):
return self.age == other.age
woman1 = Woman("Curry", 35)
woman2 = Woman("Curry", 37)
print(woman1 < woman2)
# 私有成员变量
class Phone:
__volt = None # __开头表示私有
def __keep_single(self): # 私有方法
print("单核")
def call(self): #公开方法调用私有方法
if self.__volt >= 1:
print("开发5g")
else:
self.__keep_single()
phone = Phone()
phone.call()
# 继承
class Father:
id = None
producer = "Huawei"
def call(self):
print("4g")
class Son(Father): # Son继承了Father
face_id = "0001"
def call_5g(self):
print("5g")
# 子类是对父类功能的拓展,两个类的方法都可以用
# 多继承
class grandSon(Father, Son):
pass # pass是填充空的代码段,让语法不报错的关键字
# 注意:如果在多继承中,多个父类之间成员变量有重名,括号内左边的优先
# 复写
class daughter(Father):
producer = "iPhone" # 重写父类成员
def call(self): # 重写父类成员方法
print("5g")
# 复写后调用父类原成员
print(f"原厂商是{super().producer}")
super().call()
类型注解
# 类型注解:对数据类型进行标记
# 变量的类型注解
# 基本数据类型
var_1: int = 18 # 表明var_1存储整型
var_2: str = "hello"
var_3: bool = True
# 类对象类型注解
stu: Student = Student()
# 基础容器类型注解
my_list: list = [1, 2, 3]
my_tuple: tuple = (1, 2, 3)
my_dict: dict = {"name": 666}
# 容器类型详细注解
my_list: list[int] = [1, 2, 3]
my_tuple: tuple[int, str, bool] = (1, "it", True)
my_dict: dict[str, int] = {"name": 666}
# 注释中进行注解
var_1 = random.randint(1, 10) # type: int
def func():
return 10
var_2 = func() # type: int
# 一般:在无法一眼看出是何类型的变量需要进行注解
var: int = "heima" # 即使写的类型不对,也不会报错