本文共 3389 字,大约阅读时间需要 11 分钟。
在Python编程中,类(Class)是一个非常重要的概念,它允许程序员创建自己的对象类型。这些对象类型可以包含数据(称为属性)和函数(称为方法),它们定义了这些对象的行为。
数据成员:表示事物的特征,相当于变量。
方法成员:表示事物的功能,相当于函数。
类的创建语法:
class 类名 (继承列表): 实例属性(类内的变量)定义 实例方法(类内的函数 method)定义 类变量(class variable)定义 类方法(@classmethod)定义 静态方法(@staticmethod)定义
案例:
# 定义一个类class Student: name = "小明建模" age = 30 life = 100 def fn(): print("回答我,tell me why") p1 = Student()print(p1, type(p1)) # 对象内部保存了很多数据,可以是学过的数据,函数,字符串,数字,元组,列表,字典等等print(Student.name, type(Student)) # 类属性可以通过类名访问
# 调用对象方法print(p1.name)print(p1.age)print(p1.life)print(p1.fn)
对象是类的实例化,是类的实际数据存储,具有类所定义的属性和方法。
变量存储的是实例化后的对象地址。
类参数按照初始化方法的形参传递。
对象是类的实例,具有类定义的属性和方法。
每个对象有自己的状态,但共享方法。
创建对象:
class Student: def __init__(self, name, age): print(self, name, age)p1 = Student("小明", 18)print(p1, type(p1)) 案例:
# 创建对象并访问属性和方法p1 = Student("小明", 18)p2 = Student("子恒", 21)print(p1.name)print(p2.age)print(id(p1), id(p2)) class Cat: def __init__(self, color, age): self.color = color self.age = agecat1 = Cat("red", 2)print(cat1.color)cat2 = Cat("black", 3)print(cat2.age) def关键字,第一个参数通常是self。class Box: x = 100 def __init__(self, y): self.y = y def change_y(self, new_y): print(self.y) self.y = new_yb1 = Box(99)b2 = Box(98)b3 = Box(97)print(b1.x, b2.x, b3.x)print(b1.y, b2.y, b3.y)b1.change_y(400)print(b1.y, b2.y, b3.y)print(id(b1.change_y), id(b2.change_y), id(b3.change_y))
class Qox1: x = 100 def fn(self): print(Qox1.x)b1 = Qox1()b2 = Qox1()Qox1.x = 400print(b1.x, b2.x, Qox1.x)
@classmethod装饰器,第一个参数是cls。class Box: x = 100 def __init__(self, y): self.y = y def shew(self): print(self.x, "调用shew") @classmethod def show(cls): print(cls.x, "调用show")b1 = Box(10)print(b1.x)b1.shew()print(box.x)box.show()
@staticmethod装饰器,不能接受self或cls参数。import mathclass Box: @staticmethod def volume(l, w, h): return l * w * hre = Box.volume(2, 3, 4)print(re)
__new__()负责对象的创建和内存分配。class Box: def __new__(self): print(self) return super().__new__(self)b = Box()print(b)
魔术方法是特殊的方法,用于定义对象的行为。
常见魔术方法包括:
__init__():初始化对象。__str__():定义对象的字符串表示。__repr__():定义对象的“官方”字符串表示。__len__():定义对象的长度。__getitem__():定义对象的索引操作。__setitem__():定义对象的赋值操作。__delitem__():定义对象的删除操作。__iter__():定义迭代器。__call__():定义对象作为函数的行为。案例:
class Box: def __init__(self, name, age, money): self.name = name self.age = age self.money = moneyp1 = Box("张三", "123456", 1000) 常用魔术方法示例:
def __str__(self): return "hello"def __repr__(self): return "hello2"def __len__(self): return 1000
运算符重定义示例:
def __add__(self, other): return self.money + other.moneydef __sub__(self, other): return self.money - other.moneydef __lt__(self, other): return self.money < other.moneydef __gt__(self, other): return self.money > other.moneydef __eq__(self, other): return self.money == other.money
调用对象作为函数:
def __call__(self, *args, **kwargs): print("调用了", args, kwargs) self.forward()obj = Box()obj(10, 20, 30, a=100, b=200)obj.forward() 转载地址:http://moofk.baihongyu.com/