# 设计一个类(设计一张登记表)
class Student:
name = None
gender = None
native = None
age = None
# 创建一个对象(打印一张登记表)
stu_1 = Student()
# 对象属性赋值(填表)
stu_1.name = 'jay'
stu_1.gender = "男"
stu_1.native = "福建省"
stu_1.age = 18
# 获取对象记录信息
print(stu_1.name)
print(stu_1.gender)
print(stu_1.age)
print(stu_1.native)
"""
class 类名:
类的属性(成员变量)
类的行为(成员方法)
创建对象语法:对象=类名()
"""
class Student:
name = None
def say_hi(self):
print(f'hi,{self.name}') # 注意此处,成员方法中访问成员变量必须加上self
def say_hi2(self, msg):
print(f"hi,我是{self.name},{msg}") # msg是传入形参,故不需要加self
stu_2 = Student()
stu_2.name = 'jay'
stu_2.say_hi()
stu_3 = Student()
stu_3.name = 'zhou'
stu_3.say_hi2("呀哈哈")
# 闹钟生产线
class Clock:
id = None
price = None
def ring(self):
import winsound
winsound.Beep(2000, 3000)
clock_1 = Clock()
clock_1.id = "001"
clock_1.price = 9.9
print(f"ID;{clock_1.id},价格为{clock_1.price}")
clock_1.ring()
"""
构造方法:
__init__()
在创建类对象时自动执行,
创建类对象时,将参数自动传递给__init__()方法使用
"""
class Stu:
# 构造方法中成员变量可省略
name = None
age = None
tel = None
def __init__(self, name, age, tel):
self.name = name
self.age = age
self.tel = tel
print("Stu类对象创建了一个类对象")
stu_4 = Stu("zhou", 18, "123345")
print(stu_4.name)
魔术方法
# __str__
# __lt__
# __le__
# __eq__
class Studd:
name = None
age = None
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Studd类对象,name:{self.name},age:{self.age}"
def __lt__(self, other):
return self.age < other.age
def __le__(self, other): # 此处 == 比较内存地址
return self.age <= other.age
def __eq__(self, other):
return self.age == other.age
studd = Studd("zhao", 99)
studd2 = Studd("li", 99)
print(studd)
print(str(studd))
print(studd < studd2)
print(studd > studd2)
print(studd <= studd2)
print(studd == studd2)
"""
私有成员:私有成员变量、私有成员方法,定义时以 __ 开头,仅供内部成员使用,类对象无法访问
"""
class Phone:
__current_voltage = -1
def __keep_run(self):
print("保存运行")
def call(self):
if self.__current_voltage >= 1:
print("通话中")
else:
self.__keep_run()
print("仅支持运行")
phone = Phone()
phone.call()
案例
class IPhone:
__is_5g_enable = False
def __check_5g(self):
if self.__is_5g_enable:
print("5G,启动")
else:
print("5G,关闭")
def call_by_5g(self):
self.__check_5g()
print("正在通话中")
iphone = IPhone()
iphone.call_by_5g()