1.类的创建:
在class 后面加上类的名称,类的内部包含着属性(即变量)和方法(即函数)。
class Cloud:
color = 'white'
mind = 1
size = 13.7
##属性
def run(self):
print("Cloud runs fast,but it will stay for you...")
def dream(self):
print("The dream of cloud is star")
##方法
2.类的调用:
在类后加上小括号,并将其复制至变量中,调用后的变量也就是对象,其拥有了类的属性和方法。
class Cloud:
color = 'white'
mind = 1
size = 13.7
def run(self):
print("Cloud runs fast,but it will stay for you...")
def dream(self):
print("The dream of cloud is star")
cl = Cloud()
print(cl.color)
cl.run()
cl.dream()
## white
## Cloud runs fast,but it will stay for you...
## The dream of cloud is star
3.修改不同对象的属性值:
直接通过赋值的方式修改,或是动态的创建。
class Cloud:
color = 'white'
mind = 1
size = 13.7
def run(self):
print("Cloud runs fast,but it will stay for you...")
def dream(self):
print("The dream of cloud is star")
cl = Cloud()
ca = Cloud()
ca.size = 13.19
print(cl.size)
print(ca.size)
## 13.7
## 13.19
# 由此可以看出,不同对象之间不共享属性值
cl.heavy = 520
print(cl.heavy)
## 520
4.self参数:
self参数即实例对象本身。
class Cloud:
def printCloud(self):
print(self)
c1 = Cloud()
print(c1)
c1.printCloud()
## <__main__.Cloud object at 0x0000024FFEBC7800>
## <__main__.Cloud object at 0x0000024FFEBC7800>
5.类的继承:
通过继承创建的新类称为子类,被继承的类则称为父类。
class Cloud:
def printCloud(self):
print("Cloud")
class star(Cloud):
def printStar(self):
print("Star")
#在创建的子类后加上小括号和父类的名称
c2 = star()
c2.printCloud()
c2.printStar()
## Cloud
## Star
#若子类和父类中存在相同的属性名或方法名,则按作用域相关的定义来判断。
6.isinstance()
用于判断对象是否属于某个类。
class Cloud:
def printCloud(self):
print("Cloud")
class star(Cloud):
def printStar(self):
print("Star")
c1 = Cloud()
c2 = star()
print(isinstance(c2, star))
print(isinstance(c2, Cloud))
## True
## True
# 子类的对象同样属于其父类
print(isinstance(c1, star))
print(isinstance(c1, Cloud))
## False
## True
# 反之则不然
7.issubclass()
用于检测一个类是否为某个类的子类。
class Cloud:
def printCloud(self):
print("Cloud")
class star(Cloud):
def printStar(self):
print("Star")
print(issubclass(star, Cloud))
## True
8.多重继承:Python中一个子类可以继承多个父类。
class Cloud:
def print(self):
print("Cloud")
class Wind:
def print(self):
print("Wind")
class Star(Cloud, Wind):
def printstar(self):
print("Star")
star = Star()
star.print()
## Cloud
class Cloud:
def print(self):
print("Cloud")
class Wind:
def print(self):
print("Wind")
class Star(Wind, Cloud):
def printstar(self):
print("Star")
star = Star()
star.print()
## Wind
由此可见多重继承的访问顺序为从左到右。
9.组合: