1、类的定义
class Person: #类名要单驼峰或双驼峰
#缩进
age=18 #属性
def eat(self): #self绑定实例,实例本身
#方法内容
def run(self):
#方法内容
tong=Person() #类的实例化
tong.eat() #调用类的方法
tong.run() #调用类的方法
tong.age #调用类的属性
2、含有构造方法的类
class Persion:
def __init__(self ,name,age): #__init__() 构造方法
self.name =name
self.age=age
def eat(self):
#方法内容
tong=Persion('tong',18)
一个类 里面无论是自己写还是系统自动创建,一定有__init__这个方法。
3、析构方法,__del__ ,代码执行(py文件)完成时,自动调用__del__方法,进行垃圾回收。
4、str方法
class Persion:
def __init__(self ,name,age): #__init__() 构造方法
self.name =name
self.age=age
def __str_(self):
print("wo 被调用了")
tong=A("小明",'12')
print(tong) #调用print的时候底层会调用str方法
5、应用实例
import requests
class Rectangle:
def __init__(self,length,width):
self.length=length
self.width=width
def oblong(self):
oblong_area=(self.length) * (self.width)
print(oblong_area)
oblong1=Rectangle(2,3)
oblong1.oblong()