zoukankan      html  css  js  c++  java
  • 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
    >>> 
    


  • 相关阅读:
    关于字符串循环遍历的两种方法
    Think PHP 6 .0 学习笔记
    微信小程序当前页面标题设置
    wx.showActionSheet() 选择菜单
    wx.showLoading() 加载框
    wx.showModal() 相当于 JS中的 confirm()
    wx.showToast() 显示消息提示框
    微信小程序 getLauchOprionsSync()
    怎样查看一个网站由那些服务器提供服务
    通过 bootstrap 创建好看的单选框复选框
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3196901.html
Copyright © 2011-2022 走看看