OOP definition
把一组数据结构和处理它们的方法组成对象(object),把相同行为的对象归纳为类(class),通过类的封装(encapsulation)隐藏内部细节,通过继承(inheritance)实现类的特化(specialization)和泛化(generalization),通过多态(polymorphism)实现基于对象类型的动态分派。
面向对象思想三大要素:封装、继承和多态
Class and Object
类是对象的蓝图和模板,而对象是类的实例。类是抽象的概念,而对象是具体的东西。在面向对象编程的世界中,一切皆为对象,对象都有属性和行为,每个对象都是独一无二的,而且对象一定属于某个类(型)。当我们把一大堆拥有共同特征的对象的静态特征(属性)和动态特征(行为)都抽取出来后,就可以定义出一个叫做“类”的东西。
Definition Class
在Python中可以使用class
关键字定义类,然后在类中通过之前学习过的函数来定义方法,这样就可以将对象的动态特征描述出来,代码如下所示。
"""
definition and use student class
Version: 0.1
Author: Maxwell
Date: 2024-05-03
"""
def _foo():
print('test')
class Student(object):
# __init__ is a special method to initialize when once create object.
# according to initial method to binding two attributes(name & age) for student object
def __init__(self,name,age):
self.name = name
self.age = age
def study(self, course_name):
print('%s正在学习%s.' % (self.name, course_name))
# PEP 8 requires identifiers to be named in all lowercase with multiple words connected by underscores.
# Many programmers and companies prefer to use camel case naming convention(camelCase identifiers)
def watch_av(self):
if self.age < 18:
print('%s I can only watch 《P