面向对象编程的三大特性:封装性,继承性,多态性
python创建类的标准格式:
class Animal:
num=0 #类变量
def __init__(self,aname,acolor): #构造方法
self.name=aname #成员变量
self.color=acolor
def show(self):
print("名字:{},颜色:{},数量:{}".format(self.name,self.color,Animal.num))
ani1 = Animal("fish","white") #创建Animal的实例对象
ani2 = Animal("bird","green")
ani1.show()
ani2.show()
Animal.num=2 #通过类名来赋值
ani1.show()
ani2.show()
名字:fish,颜色:white,数量:0
名字:bird,颜色:green,数量:0
名字:fish,颜色:white,数量:2
名字:bird,颜色:green,数量:2
1.类是描述一组对象的共同特征(成员变量)和行为(方法),在创建对象之前要定义一个类。
2.创建对象时,就会自动为新生成的对象调用构造方法。
class Dog:
......
def show(self,weight):
print("重量{}".format(weight))
print("颜色{}".format(self.color))
dog = Dog(color="grey")
dog.weight = 52 #添加构造方法中没有的属性,在show方法中添加参数weight
dog.show(dog.weight)
3.添加属性,调用该方法
构造方法&析构方法
#无参构造方法
def __init__(self):
self.attribute = "string"
#有参构造方法
def __init(self, attri1= "",attri2=""):
self.attri1=attri1
self.attri2=attri2
#析构方法
def __del__(self):
print("Object deleted&