目录
1、Python的类如何定义?
class Fruit:
# 类属性
price = 0 # 通过类名和对象名都可见
def __init__(self):
self.__color="Red" # 定义和设置私有属性
self.__city = 'beijing' # 定义和设置私有属性
def __outputColor(self): # 定义私有方法
print(self.__color)
def __outputCity(self): # 定义私有方法
print(self.__city)
def output(self): # 定义共有方法
self.__outputColor()
self.__outputCity()
@ staticmethod
def getPrice(): # 定义静态方法
return Fruit.price
@ staticmethod
def setPrice(p):
Fruit.price = p
python的类定义也离不开关键字class,属性(成员变量)有两种,一种是实例属性,一种是类属性。其中实例属性是在构造函数__init__()中定义的。
2、访问成员或调用方法
from Fruit import Fruit
if __name__ == '__main__':
apple = Fruit()
# 通过对象名访问公有方法
apple.output()
# 通过类名访问公邮方法
Fruit.output(apple)
# 通过对象名访问静态方法
apple.setPrice(23)
print(apple.price)
# 通过类名访问静态方法
print(Fruit.getPrice())
Fruit.setPrice(100)
print(Fruit.getPrice())
3、类的继承
class Animal:
def run(self):
print('Animal is running')
class Cat(Animal):
def run(self):
python中的继承是子类名之后的括号中写明父类名,与java不同,Java用关键字extends 标识。
4、python中的多态
class Animal:
def run(self):
print('Animal is running')
class Cat(Animal):
def run(self):
print('cat is running')
class Dog(Animal):
def run(self):
print('dod is running')
if __name__ == '__main__':
cat = Cat()
dog = Dog()
a = Animal()
cat.run()
dog.run()
a.run()
打印结果:
cat is running
dod is running
Animal is running
总结:子类会覆盖父类中的run方法。