Python的面向对象编程:把一组数据结构和处理他们的方法组成对象(object),把相同行为的对象归纳为类(class),通过类的封装(encapsulation)隐藏内部细节,通过继承(inheritance)实现类的特化(specification)/泛化(generalization),通过多态(polymorphism)实现基于对象类型的动态分派(dynamic dispatch)

1. 封装(encapsulation)

2. 继承(inheritance)

3. 多态(polymorphism)

4. 初始化函数 -- init(self, *args, **kwargs)

5. 类方法第一个参数是类cls,用@classmethod装饰

6. 对象方法第一个参数是对象self,不需要任何修饰

7. 静态方法第一个参数没有要求,用@staticmethod装饰

8. python的访问控制不严格:

  1. 以两个下划线开始,以两个下划线结束的变量,是一些特殊变量,一般不要自己定义
  2. 以两个下划线开始的变量是私有(private)变量,只能在类内部访问
  3. 以一个下划线开始的变量,虽然时公开(public)的变量,但是一般这些变量不建议直接访问
  4. 对于私有(private)变量依然有方法去访问:_className__varName。不推荐。 #### 9. 获取对象信息的方法
  5. 使用type()获得变量的类型信息
  6. 使用types模块:types.FunctionType, types.BuiltinFunctionType, types.LambdaType, types.GeneratorType
  7. 使用isinstance()
  8. 使用dir()获取对象的所有属性和方法
  9. 使用getattr(), setattr()和hasattr()来操作对象的状态 #### 10. 区分对象属性和类属性

In [4]:
class Student(object):
    def __init__(self, score):
        self.__score = score
    def print_score(self):
        print('The score is %d' %self.__score)
        
student = Student(90)
student.print_score()
print(student._Student__score)
print(student.__score)


The score is 90
90
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-cfdd70776bf1> in <module>()
      8 student.print_score()
      9 print(student._Student__score)
---> 10 print(student.__score)

AttributeError: 'Student' object has no attribute '__score'

In [ ]: