码迷,mamicode.com
首页 > 其他好文 > 详细

User-defined types

时间:2014-09-24 01:28:45      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   for   2014   sp   cti   

We have used many of Python’s built-in types; now we are going to define a new type. As an example, we will create a type called Point that represents a point in two-dimensional space.

In mathematical notation, points are often written in parentheses with a comma separating the coordinates. For example, (0,0) represents the origin, and (x,y) represents the point x units to the right and y units up from the origin.

There are several ways might represent points in Python:

  • We could store the coordinates separately in two variables, x and y.
  • We could store the coordinates as elements in a list or tuple.
  • We could create a new type to represent points as objects.

Creating a new type is more complicated than other options, but it has advantages that will be apparent soon. A user-defined type is also called a class. A class definition looks like this:

 bubuko.com,布布扣                      

This header indicates that the new class is called Point. The body is a docstring that explains what the class is for.

bubuko.com,布布扣

Because Point is defined at the toplevel, its ‘full name’ is __main__.Point. The class object is like a factory for creating objects. To create a Point, you call Point as if it were a function. The return value is a reference to a Point object, which we assign to blank. Creating a new object is called instantiation, and the object is an instance of the class.

 

from Thinking in Python

User-defined types

标签:style   blog   http   io   ar   for   2014   sp   cti   

原文地址:http://www.cnblogs.com/ryansunyu/p/3989516.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!