目录
一、类的定义与对象创建
在Python中,类是一种自定义的数据类型,用于封装数据和行为。下面是最基本的类定义方式:
# 类的定义
class Human:
pass
print(type(Human)) # 输出:<class 'type'>
# 创建对象
teacher = Human()
print(id(teacher)) # 输出对象的内存地址
student1 = Human()
print(id(student1)) # 输出另一个对象的内存地址
每个对象都是类的实例,拥有独立的内存空间。id()
函数可以获取对象的内存地址,验证它们是不同的实例。
二、对象属性与构造函数
我们可以通过__init__
方法(构造函数)为类添加属性:
class Human:
# 构造函数(方法):函数名是固定的 __init__
# 至少有一个参数:self
def __init__(self, name, birthday, gender):
self.birthday666 = birthday # 属性名可以自定义
self.gender = gender
self.name = name
# 对象:类的实例化
p1 = Human("小米", "2003-06-03", "Male")
print(f"大家好,我是{p1.name},生于{p1.birthday666}")
# 使用字典解包方式创建对象
student = {
"name": "肖三",
"gender": "先生",
"birthday": "2003-08-08",
}
p2 = Human(**student) # **用于解包字典
print(p2.name)
构造函数在对象创建时自动调用,用于初始化对象属性。属性名可以自定义,但建议使用有意义的名称。
三、对象方法
类不仅可以包含属性,还可以定义方法(函数):
class Human:
def __init__(self, name, birthday, gender):
self.birthday666 = birthday
self.gender = gender
self.name = name
# 动作定义成方法
def introduction(self):
print(self) # 打印对象信息
return f"我是{self.name},出生于{self.birthday666}"
# 对象:类的实例化
p1 = Human("小米", "2003-06-03", "Male")
print("p1的内存空间:", "0x" + str(hex(id(p1)))[2:].upper().rjust(16, "0"))
itr = p1.introduction() # 调用方法
# 等价于:itr = Human.introduction(p1)
print(itr)
方法必须包含self
参数,它指向当前对象实例。可以通过实例调用方法,也可以通过类名调用(需要显式传入实例)。
四、实用案例:查找二维列表元素
下面是一个实用案例,演示如何用类处理二维列表:
"""
list1=[
[1.0, 2.2, 3.0, 4.0, 5.0],
[21.0, 22.2, 23.0, 24.0, 25.0],
[31.0, 32.2, 33.0, 34.0, 35.0],
[41.0, 42.2, 43.0, 44.0, 45.0],
]
写个类:
去找具体指定的值x后面的n个元素
比如:x=42.2 n=3 ---> 43.0, 44.0, 45.0
"""
class FindItems:
def __init__(self, list100):
self.list666 = list100 if isinstance(list100, list) else list(list100)
self.rows = len(list100) # 行数
self.cols = len(list100[0]) if self.rows else 0 # 列数
def find(self, target, count):
for r in range(self.rows):
for c in range(self.cols):
if self.list666[r][c] == target:
return self.list666[r][c + 1 : (c + 1 + count)]
return None
if __name__ == "__main__":
list1 = [
[1.0, 2.2, 3.0, 4.0, 5.0],
[21.0, 22.2, 23.0, 24.0, 25.0],
[31.0, 32.2, 33.0, 34.0, 35.0],
[41.0, 42.2, 43.0, 44.0, 45.0],
]
obj1 = FindItems(list1)
res = obj1.find(42.2, 3) # 输出:[43.0, 44.0, 45.0]
print(res)
res1 = obj1.find(24.0, 5) # 输出:[25.0]
print(res1)
res2 = obj1.find(29.0, 5) # 输出:None
print(res2)
这个类封装了二维列表的处理逻辑,提供了查找指定元素后n个元素的功能。
五、模拟内置str类的实现
我们甚至可以模拟Python内置类的行为:
class str:
def __init__(self, value):
# 推导式把字符串转为list:可变类型
self.value = [item for item in value]
def capitalize(self):
newchar = [
chr(ord(item) + 32) if (65 <= ord(item) <= 90) else item
for item in self.value
]
for i in range(len(self.value)):
if i == 0:
newchar[0] = (
chr(ord(self.value[0]) - 32)
if ord(self.value[0]) > 96
else self.value[0]
)
continue
if self.value[i] == " ":
newchar[i + 1] = (
chr(ord(self.value[i + 1]) - 32)
if ord(self.value[i + 1]) > 96
else self.value[i + 1]
)
i += 1
str2 = ""
for item in newchar:
str2 += item
return str2
if __name__ == "__main__":
print(ord("z")) # 输出:122
str1 = str("How old aRe you?")
print(str1.capitalize()) # 输出:How old are you?
这个示例展示了如何实现字符串的capitalize()
方法,将字符串首字母大写,其余字母小写。
总结
本文介绍了Python类的基本概念,包括:
-
类的定义与对象创建
-
构造函数与对象属性
-
对象方法的定义与使用
-
实际应用案例
-
模拟内置类的实现
类作为面向对象编程的核心概念,能够帮助我们更好地组织代码,实现封装、继承和多态等特性。通过实践这些基础示例,可以逐步掌握Python类的使用技巧。