本文已参与「新人创作礼」活动,一起开启掘金创作之路。
1.初识
-
设计类
class Student: name = None -
创建对象
stu_1 = Student() stu_2 = Student() -
对象属性赋值
stu_1.name = "张三"
2.类的定义
class 类名称: class 是关键字, 表示要创建类了
属性: 成员变量
行为: 成员方法
方法的定义:
def 方法名(self, 形参1, 形参2....)
do something...
- self也是一个关键字, 定义成员的时候必须填写
- 用来表示类对象自身的意思
- 在方法内部, 要访问类的成员变量, 必须使用self
- 调用方法时候, 传参可以忽略self
使用:
对象 = 类名称()
class Student:
name = None
age = None
def sayHi(self):
print(f"hello world, my name is {self.name}")
class Clock:
id = None
price = None
def ring(self):
import winsound
winsound.Beep(2500, 3000) # 使系统发出声音
clock1 = Clock()
clock1.id = 3233
clock1.price = 20.01
clock1.ring()
3.其他赋值方法
1.构造方法传参
python类可以使用 __init__() 方法, 称之为构造方法
可以实现:
- 在创建类对象(构造类)的时候, 会自动执行
- 在创建类对象(构造类)的时候, 将参数自动传递给
__init__()方法使用
class Student:
name = None # 这三个可以省略
age = None # 这三个可以省略
tel = None # 这三个可以省略
def __init__(self, name, age, tel):
self.name = name
self.age = age
self.tel = tel
stu_01 = Student("张三", 23, '18712345678')
上面的成员定义可以省略:
class Student:
def __init__(self, name, age, tel):
self.name = name
self.age = age
self.tel = tel
stu_01 = Student("张三", 23, '18712345678')
2.其他相关的方法
1. __str__ : 字符串方法
class Student:
def __init__(self, name, age, tel):
self.name = name
self.age = age
self.tel = tel
def __str__(self):
return f'name={self.name}, age={self.name}, tel={self.tel}'
stu_01 = Student("张三", 23, "123459789")
print(stu_01)
- 返回值是个字符串
- 自定义值
- 相当于
toString()方法
2.__lt__ 小于符号和大于符号的比较
class Student:
def __init__(self, name, age, tel):
self.name = name
self.age = age
self.tel = tel
def __lt__(self, other):
return self.age < other.age
stu_01 = Student("张三", 23, "123459789")
stu_02 = Student("李四", 24, "123459789")
print(stu_01 < stu_02)
3.__le__ 用于小于等于和大于等于
class Student:
def __init__(self, name, age, tel):
self.name = name
self.age = age
self.tel = tel
def __le__(self, other):
return self.age <= other.age
stu_01 = Student("张三", 23, "123459789")
stu_02 = Student("李四", 24, "123459789")
print(stu_01 <= stu_02)
4.__eq__ 比较运算符实现方法
- 不实现
__eq__, 对象之间可以比较, 但是比较的是内存地址, 不同对象一定是False - 实现
__eq__, 就可以自定义两个对象进行比较了
class Student:
def __init__(self, name, age, tel):
self.name = name
self.age = age
self.tel = tel
def __eq__(self, other):
return self.age == other.age
stu_01 = Student("张三", 23, "123459789")
stu_02 = Student("李四", 24, "123459789")
print(stu_01 == stu_02)
4.封装
类中提供了私有成员的形式来支持:
- 私有成员变量
- 私有成员方法
定义私有成员的方法非常简单, 只需要:
- 私有成员变量: 变量名以
__开头(2个下划线) - 私有成员方法: 方法名以
__开头(2个下划线)
就可以完成私有成员的设置
私有成员无法被类对象使用, 但是可以被其他的成员使用
class Phone:
__current_voltage = 0.5 # 私有成员变量
def __keep_single_core(self): # 私有成员方法
print("让cpu以单核模式运行")
def call_by_5g(self):
if self.__current_voltage >=1:
print("5g通话已经开启")
else:
self.__keep_single_core()
print("电量不足, 无法开启5g模式, 设置为单核运行")