程序界运粮官 2022-01-15 03:58:38 阅读数:721
原文链接
https://blog.csdn.net/weixin_51380973/article/details/117931550
1. 点标记法访问属性和方法,同java:
class Point:
"""Represents a point in 2-D space.
attributes: x, y
"""
blank = Point()
blank.x = 3
blank.y = 4
2. 对象支持嵌套,java未知:
class Rectangle:
"""Represents a rectangle.
attributes: width, height, corner.
"""
box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0
示例中corner对象嵌套了一个Point对象。
3.实例可做返回值,同java
def find_center(rect):
"""Returns a Point at the center of a Rectangle.
rect: Rectangle
returns: new Point
"""
p = Point()
p.x = rect.corner.x + rect.width/2.0
p.y = rect.corner.y + rect.height/2.0
return p
center = find_center(box)
print('center', end=' ')
print_point(center)
4. 类中可以不定义属性和方法,对象可以自嗨,java大不同:
class Point:
"""Represents a point in 2-D space.
attributes: x, y
"""
def print_point(p):
"""Print a Point object in human-readable format."""
print('(%g, %g)' % (p.x, p.y))
def main():
blank = Point()
blank.x = 3
blank.y = 4
print('blank', end=' ')
print_point(blank)
if __name__ == '__main__':
main()
参考文档:
https://github.com/AllenDowney/ThinkPython2
https://blog.csdn.net/weixin_51380973/article/details/117931550
版权声明:本文为[程序界运粮官]所创,转载请带上原文链接,感谢。 https://blog.csdn.net/weixin_51380973/article/details/117931550