定义方式:在Python中,类是使用class关键字定义的。
类名采用首字母大写的驼峰命名法,比如学生的家庭作业,就用StudentHomework来定义这个类。
类定义了对象的属性和方法,实例是类的具体实现。
本质:类是现实世界或思维世界中的实体在计算机中的反映。核心功能:将数据及对这些数据的操作封装在一起。
组成要素:
属性(数据成员):描述事物的特征(如Student类中的name和age)。
方法:描述事物的行为(如do_homework方法)。
init()方法是类的构造方法,在创建类的实例时会自动调用
#首先了解类的创建过程,类是模板
classDog():
#__init__ 类的身体
def__init__(self,name,age):
self.name = name
self.age = age
第一个参数为 self,可以访问实例属性和其他实例方法。
最常用的方法
classDog():
def__init__(self,name,age,color):#狗的属性
self.name = name
self.age = age
self.color = color
defsit(self): #狗的行为
print("我坐下来了")
defroll_over(self):
print("我正在打滚")
dog1 = Dog("大白", 2, "黑色")
dog1.color
'黑色'
dog1.sit()
我坐下来了
classDog():
def__init__(self,name,age,color):#狗的属性、特征
self.name = name
self.age = age
self.color = color
defsit(self): #狗的行为
print(self.name+"我坐下来了")
defroll_over(self):
print(self.name+"我正在打滚")
## 实例 实际例子
# 对象名 也是一个 变量名
dog1 = Dog("大白", 2, "黑色")
dog1.age
2
dog2 = Dog("小小",3,"黑白")
dog2.name
'小小'
dog1.sit()
大白我坐下来了
dog2.sit()
小小我坐下来了
defroll_over():
print("Roll over!")
roll_over()
Roll over!
dog1.roll_over()
dog2.roll_over()
大白我正在打滚
小小我正在打滚
classCar():
def__init__(self, maker, model, year):
self.maker = maker
self.model = model
self.year = year
self.mileage = 0
defdescribe(self):
print(self.maker+" "+self.model+" "+self.year)
defget_mileage(self):
print("这个车已经跑了"+str(self.mileage)+"公里!")
ad = Car("奥迪", "K1", "2010") #创建真实汽车
ad.describe()
奥迪 K1 2010
baoma = Car("宝马", "X5", "2018")
baoma.describe()
宝马 X5 2018
classCar():
def__init__(self, maker, model, year):
self.maker = maker
self.model = model
self.year = year
self.mileage = 0
defset_mileages(self,mileage):
ifself.mileage < mileage:
self.mileage = mileage
defadd_mileage(self,mileage):
if mileage>=0:
# self.mileage +=mileage
self.mileage = self.mileage + mileage
car1 = Car("奥迪", "K1", "2010")
car1.mileage
0
# Ensure the Car class with the set_mileage method is used
car1.set_mileages(1001)
car1.mileage
1001
car1.add_mileage(10)
car1.mileage
1011
在 Python 中:普通属性:没有下划线,随便用。
受保护属性:前面加一个 _,比如 _name。 语义上表示:这是“内部用的”,外部尽量别动,但其实外部仍能访问。
私有属性:前面加两个下划线 __,比如 __name。 Python 会做名字改写(Name Mangling),在类外不能直接用 obj.__name,而是 _类名__name 才能访问。
classPerson:
def__init__(self, name, age):
self.name = name # 普通属性
self._gender = "未知"# 受保护属性
self.__age = age # 私有属性
defshow_age(self):
returnself.__age
Tom1 = Person("Tom", 18) #实例化
# 访问普通属性
Tom1.name
'Tom'
# 访问受保护属性
Tom1._gender
'未知'
# 通过类内方法访问
Tom1.show_age()
18
# 或者通过“名字改写”访问
Tom1._Person__age
18
类方法
使用装饰器 @classmethod,第一个参数为 cls(代表类本身)。 可以访问和修改类属性,但不能访问实例属性。 可以通过类名或实例调用。即可以在没有实例的情况下被调用。
静态方法
使用装饰器 @staticmethod,没有特殊的第一参数。 本质上就是普通函数,但放在类的命名空间中组织代码。 不能访问类属性或实例属性(除非通过传参)。
classMyClass():
class_attr = 10# 类属性
@classmethod
defclass_method(cls, x):
# 在类方法中可以访问类的属性
print(f"Class attribute: {cls.class_attr}")
print(f"Received value: {x}")
# 通过类名调用类方法
MyClass.class_method(5)
# 通过实例对象调用类方法
obj = MyClass()
obj.class_method(7)
Class attribute: 10
Received value: 5
Class attribute: 10
Received value: 7
classMyClass():
@staticmethod
defmy_static_method(arg1, arg2):
# 静态方法的实现
return arg1 + arg2
# 静态方法可以通过类名直接调用,也可以通过类的实例调用:
# 通过类名调用
result = MyClass.my_static_method(1, 2)
result
3
# 通过实例调用
obj = MyClass()
result = obj.my_static_method(3, 4)
result
7
classMathUtils:
@staticmethod
defadd(x, y):
return x + y
@staticmethod
defmultiply(x, y):
return x * y
# 使用静态方法
MathUtils.add(5, 3)
8
MathUtils.multiply(5, 3)
15
在上面这个例子中,add 和 multiply 是静态方法,它们不依赖于 MathUtils 类的任何状态,只是提供了简单的数学运算功能。
classCalculator():
# 类属性
pi = 3.14159
def__init__(self, value):
self.value = value # 实例属性
# 实例方法:需要 self
defsquare(self):
returnself.value ** 2
# 类方法:通过 cls 操作类属性
@classmethod
defcircle_area(cls, radius):
"""计算圆的面积,使用类属性 pi"""
return cls.pi * radius ** 2
# 静态方法:不需要 self 或 cls,工具函数
@staticmethod
defis_positive(number):
return number > 0
# 调用实例方法
calc = Calculator(5)
calc.square()
25
# 调用类方法:可以直接用类名调用
Calculator.circle_area(10)
314.159
# 调用静态方法
print(Calculator.is_positive(-3)) # 输出:False
print(calc.is_positive(8)) # 也可以实例调用,输出:True
False
True
# 定义Student类
classStudent:
# 构造方法,初始化name和age属性
def__init__(self, name, age):
self.name = name
self.age = age
# 自定义__eq__方法,用于比较两个Student对象的age是否相等
def__eq__(self, other):
# 返回self的age与other的age是否相等的布尔值
returnself.age == other.age
# 创建第一个Student对象stu1
stu1 = Student("周杰伦", 11)
# 创建第二个Student对象stu2
stu2 = Student("林俊杰", 17)
# 比较stu1和stu2是否相等(实际调用__eq__方法比较age)
stu1 == stu2 #
# stu1.__eq__(stu2)#
False
classStudent:
# 初始化方法,定义name和age属性
def__init__(self, name, age):
self.name = name
self.age = age
# 自定义小于比较方法__lt__,比较两个对象的age
def__lt__(self, other):
returnself.age < other.age
# 创建两个Student实例
stu1 = Student("周杰伦", 11)
stu2 = Student("林俊杰", 13)
# 调用__lt__方法比较stu1和stu2的age
print(stu1 < stu2) # 输出:True
# 调用__lt__的反向逻辑(大于)
print(stu1 > stu2) # 输出:False
True
False
classFather():
def__init__(self):
self.a='eee'
defaction(self):
print('调用父类的方法')
classSon(Father):
pass
son1=Son() # 子类Son 继承父类Father的所有属性和方法
son1.action() # 调用父类方法
调用父类的方法
son1.a # 调用父类属性
'eee'
classFather():
def__init__(self,value):
self.a=value
defaction(self):
print('调用父类的方法')
classSon(Father):
def__init__(self,value):
super().__init__(value)
son=Son(5) # 子类Son 继承父类Father的所有属性和方法
son.action() # 调用父类方法
调用父类的方法
son.a # 调用父类属性
5
classPerson():
def__init__(self,name,age):
self.name = name
self.age = age
defeat(self):
print(self.name+"正在吃饭")
defsleep(self):
print(self.name+"正在睡觉")
p1 = Person("siki",20)
p1.eat()
siki正在吃饭
classTeacher(Person):
def__int__(self,name,age):
super().__init__(name,age)#调用父类里面的初始化方法,构造方法
t1 = Teacher("chen",30)
t1.sleep()
chen正在睡觉
classPerson():
def__init__(self,name,age):
self.name = name
self.age = age
defeat(self):
print(self.name+"正在吃饭")
defsleep(self):
print(self.name+"正在睡觉")
classTeacher(Person):
def__init__(self,name,age,course):
super().__init__(name,age) #调用父类里面的初始化方法,构造方法
self.course = course #子类自己属性
# 子类方法
defteach(self):
print(self.name+'正在教'+self.course+'课程')
#重写父类方法
defeat(self):
print(self.name+"去食堂吃饭")
t1 = Teacher("zhang",28,"python")
t1.eat()
zhang去食堂吃饭
t1.teach()
zhang正在教python课程
一般都会这样说:“函数就是定义在类外面的,而方法就是定义在类里面的,跟类绑定的”
函数是一段完成特定任务的独立代码块,可以直接调用。而方法是与对象关联的函数,必须通过对象来调用。
deftest1():
print('这是方法还是函数?')
import inspect
print(inspect.isfunction(test1)) # True
True
print(inspect.ismethod(test1)) # False
False
内置函数: 内置函数是Python解释器直接提供的函数,伴随着Python解释器一起启动,无需导入任何模块即可使用。
它们通常用于完成一些通用操作,例如 len()、print()、range() 等。
# 内置函数
print(len("Python")) # len() 是内置函数
print(max(10, 20)) # max() 是内置函数
6
20
# 方法
text = "hello"
print(text.upper()) # upper() 是字符串对象的方法
HELLO
my_list = [1, 2, 3]
my_list.append(4) # append() 是列表对象的方法
print(my_list)
[1, 2, 3, 4]
my_list = [1,4,3]
# 使用类的方法排序
my_list.sort()
my_list
[1, 3, 4]
my_list = [1,4,3]
# 使用内置函数
new_list = sorted(my_list)
new_list
[1, 3, 4]