面向对象
面向对象三大特性
封装
---将属性和方法书写到类的里面的操作即为封装
---封装可以为属性和方法添加私有权限
继承
---子类默认继承父类的所有属性和方法
---子类可以重写父类属性和方法
多态
---传入不同的对象,产生不同的结果
class Dog(object):
def work(self):
print('工作!')
class ArmyDog(Dog):
def work(self):
print('ArmyDog 追击敌人!')
class DrugDog(Dog):
def work(self):
print('DrugDog 缉查毒品!')
class Person(object):
def work_with_dog(self, dog):
dog.work()
aDog = ArmyDog()
bDog = DrugDog()
p = Person()
p.work_with_dog(aDog)
p.work_with_dog(bDog)
类属性和实例属性
# 定义类属性
class Dog(object):
tooth = 10
# 调用类属性
print(Dog.tooth)
# 创建实例属性
personTooth = Dog()
# 调用实例属性
print(personTooth.tooth)
print('-' * 25)
# 修改类属性
# 通过类去修改
Dog.tooth = 20
print(Dog.tooth)
print(personTooth.tooth)
print('-' * 25)
# 通过实例去修改
personTooth.tooth = 35
print(Dog.tooth)
print(personTooth.tooth)
print('-' * 25)
类方法和静态方法
# 1.定义类:私有属性,类方法获取这个私有类属性
class Dog(object):
__tooth = 10
# 定义类方法
@classmethod
def get_tooth(cls):
return cls.__tooth
# 创建对象,调用方法
dog = Dog()
print(dog.get_tooth())
print(Dog.get_tooth())
静态方法
class Dog(object):
@staticmethod
def info_print():
print('这是一个静态方法')
wangcai = Dog()
wangcai.info_print()
Dog.info_print()