与 C++ 不合的是,“成员变量”必须要加 self. 前缀,不然就变成类的属性(相当于 C++ 静态成员),而不是对象的属性了。
拜访控制
Python 没有 public / protected / private 如许的拜访控制,如不雅你非要表示“私有”,习惯是加双下划线前缀。
- class Point:
- def __init__(self, x=0, y=0):
- self.__x, self.__y = x, y
- def set(self, x, y):
- self.__x, self.__y = x, y
- def __f(self):
- pass
__x、__y 和 __f 就相当于私有了:
- >>> p = Point(10, 10)
- >>> p.__x
- ...
- AttributeError: 'Point' object has no attribute '__x'
- >>> p.__f()
- ...
- AttributeError: 'Point' object has no attribute '__f'
_repr_
测验测验打印 Point 实例:
Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics.
这两者都是对象的字符串情势的表示,但照样有点差其余。简单来说,repr() 的结不雅面向的是说冥器,平日都是合法的 Python 代码,比如 Point(10, 10);而 str() 的结不雅面向用户,更简洁,比如 (10, 10)。
- >>> p = Point(10, 10)
- >>> p
- <point.Point object at 0x000000000272AA20>
平日,这并不是我们想要的输出,我们想要的是:
请推敲 Shape.area() 除了简单的返回 0.0,有没有更好的实现?
- >>> p
- Point(10, 10)
添加特别办法 __repr__ 即可实现:
- class Point:
- def __repr__(self):
- return 'Point({}, {})'.format(self.__x, self.__y)
- >>> repr(p)
- 'Point(10, 10)'
_str_
如不雅没有供给 __str__,str() 缺省应用 repr() 的结不雅。
即使如斯,你是无法禁止用户实例化 AbstractEventLoop 的:
按照这个原则,我们为 Point 供给 __str__ 的定义如下:
_add_
两个坐标点相加是个很合理的需求。
- >>> p1 = Point(10, 10)
- >>> p2 = Point(10, 10)
推荐阅读
在这个语法树构造中,body里包含着if构造中的语句return HttpResponse("2"),type为Compare表示该构造体为断定语句,left表示左值即源码中的type,test构造体中则是用来进行if断定,test中的ops对应着>>>详细阅读
本文标题:浅析Python的类、继承和多态
地址:http://www.17bianji.com/lsqh/36335.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示