文章目录
1.类的定义
#(一)面向对象编程
例1.1在python中,可以使用class关键字来声明一个类,基本语法格式如下:
class 类名:
类的属性
类的方法
class cat:
#属性
#方法
def eat(self):
print(“------吃鱼--------”)
例1.2根据类创建对象
对象名=类名()
例如,创建cat类的一个对象a,示例代码如下:
a=cat()
在上述代码中,cat实际是一个变量,可以使用它访问类的属性和方法。要想给对象添加属性,可以通过如下方式:
对象名.新的属性值
例如,使用a给cat类的对象添加color属性,示例代码如下:
a.color="黑色"
接下来通过完整的案例演示如何创建对象,添加属性并且调用方法,如例1-1所示。
#定义类
class car:
#移动
def move(self):
print("车子在奔跑")
#鸣笛
def toot(self):
print("车在鸣笛...嘟嘟..")
#创建一个对象,并用变量jeep保存它的引用
jeep=car()
#添加表示颜色的属性
jeep.color="黑色"
#调用方法
jeep.move()
jeep.toot()
#访问属性
print(jeep.color)
运行结果如下
F:\python\python.exe C:/Users/小白/PycharmProjects/untitled/char11.py
车子在奔跑
车在鸣笛...嘟嘟..
黑色
Process finished with exit code 0
2.构造方法和析构方法
例1.3使用构造方法
class car:
#构造方法
def __init__(self):
self.color='黑色'
#鸣笛
def toot(self):
print('%s的车在鸣笛'%(self.color))
#创建一个对象,并用变量ly保存它的引用
ly=car()
ly.toot()
程序运行结果如下:
F:\python\python.exe C:/Users/小白/PycharmProjects/untitled/111.py
黑色的车在鸣笛
Process finished with exit code 0
例1.4使用代参构造方法
#定义类
class gdt:
#带参构造方法
def __init__(self,c):
self.s=c
def name(self):
print('%s 扈'%(self.s))
def age(self):
print('%s 20'%(self.s))
hly=gdt('omgdggogoing')
lyy=gdt('年龄')
lyy.age()
hly.name()
运行结果如下:
F:\python\python.exe C:/Users/小白/PycharmProjects/untitled/111.py
年龄 20
omgdggogoing 扈
Process finished with exit code 0
例1.5析构方法
当删除一个对象来释放类所占用资源的时候,python解释器默认会调用另一个方法,这个方法就是__del__方法。
使用析构方法
#定义类
class people:
def __init__(self,name,age):
self.name=name
self.age=age
def __del__(self):
print('--------------del---------------')
people=people('扈刘阳','20')
del people
print('**************1***************')
运行结果如下:
F:\python\python.exe C:/Users/小白/PycharmProjects/untitled/111.py
--------------del---------------
**************1***************
Process finished with exit code 0