Python 中的用户自定义类型

Python中面向对象的技术

              Python是面向对象的编程语言,自然提供了面向对象的编程方法。但要给面向对象的编程方法下一个定义,是很困难的。问题关键是理解对象
的含义。对象的含义是广泛的,它是对现实世界和概念世界的抽象、模拟和提炼。


对象的方法与函数类似,但是还有两方面的区别:

1-方法定义在类的内部,是类的一部分,他们之间的关系是很明显的;

2-调用的语法不一样;

>>> class Time:
...     pass
...     
... 
>>> def printTime(time):
...     print str(time.hours)
...     
... 
>>> now = Time();
>>> now.hours = 10;
>>> printTime(now)
10
>>> 


我们通过改变缩进可以改变函数的作用域的归属:

>>> class Time:
...     def printTime(self):
...         print str(self.hours)
...         
...     def increment(self,hours):
...         self.hours = hours + self.hours
...         while self.hours >= 12:
...             self.hours = self.hours - 12
...             self.day = self.day + 1
...             
...         
...     
... 
>>>


可选择的参数

我们曾见到一些内置的函数,能够接受的参数个数是可变的。同样,你也能够定义可变参数的函数。下面这个函数求从数head开始,到tail为尾,步长为step的所有数之和。

>>> def total(head,tail,step):
...     temp = 0;
...     while head <= tail:
...         temp = temp + head;
...         head = head + step;
...         
...     return temp;
...     
... 
>>> total(1,100)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: total() takes exactly 3 arguments (2 given)
>>> total(1,100,3)
1717
>>> def total(head,tail,step = 2):
...     temp = 0;
...     while head <= tail:
...         temp = temp + head;
...         head = head + step;
...         
...     return temp;
...     
... 
>>> total(1,100);
2500
>>> total(1,100,3);
1717
>>> 


原文地址:https://www.cnblogs.com/dyllove98/p/3196901.html