006 python语法_002 函数/类/模块

Posted 汁虫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了006 python语法_002 函数/类/模块相关的知识,希望对你有一定的参考价值。

 

 

 

\'\'\'
时间:2018/10/11
目录: 
  一: 函数
          1 定义函数
      2 空函数
      3 参数 - 检查
      4 参数 - 返回多个值
      5 参数 - 默认参数
      6 参数 - 可变参数
      7 参数 - 关键字参数
      8 参数 - 命名关键字参数   二: 类 1 定义 2 初始化
      3 继承   三: 模块
      1 使用模块
      2 自编模块
\'\'\'

 

一: 函数
  1 定义函数

#coding:utf-8

def myAbs(nNum):
    if nNum >= 0:
        return nNum
    else:
        return -nNum

nNum = myAbs(33)
print(nNum)

nNum = myAbs(-33)
print(nNum)
33
33

  

  2 空函数

# coding:utf-8
def nop():
    pass    #pass作占位符,还没想好写代码

print(nop())
print(type(nop()))
None
<class \'NoneType\'>

 

   3 参数 - 检查

#coding:utf-8

def myAbs(nNum):
    if not isinstance(nNum, (int, float)):      # 类型检查
        raise TypeError(\'bad operand type\')     # 错误提示
    if nNum >= 0:
        return nNum
    else:
        return -nNum


nNum = myAbs(33)
print(nNum)

nNum = myAbs(-33)
print(nNum)

nNum = myAbs("33")
print(nNum)
Traceback (most recent call last):
33
  File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/StudyJson/StudyJson/Study001.py", line 18, in <module>
33
    nNum = myAbs("33")
  File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/StudyJson/StudyJson/Study001.py", line 5, in myAbs
    raise TypeError(\'bad operand type\')     # 错误提示
TypeError: bad operand type

 

  4 参数 - 返回多个值

# coding:utf-8
def Test(x, y):
    dictTest = {
        "name": "ZS",
        "age": y + 1,
        "sex": "m"
    }
    return x, y, x + y, dictTest

nNum = Test(1, 2)
print(nNum)
print(type(nNum))

i1, i2, i3, dictTest = Test(1, 2)
print(i1)
print(type(i3))
print(i2)
print(type(i3))
print(i3)
print(type(i3))
print(dictTest)
print(type(dictTest))
(1, 2, 3, {\'name\': \'ZS\', \'age\': 3, \'sex\': \'m\'})
<class \'tuple\'>
1
<class \'int\'>
2
<class \'int\'>
3
<class \'int\'>
{\'name\': \'ZS\', \'age\': 3, \'sex\': \'m\'}
<class \'dict\'>

 

  5 参数 - 默认参数

# coding:utf-8

def enroll(name, gender, age=6, city=\'Beijing\'):
    print(\'name:\', name)
    print(\'gender:\', gender)
    print(\'age:\', age)
    print(\'city:\', city, end="\\n\\n")

enroll(\'Bob\', \'M\', 7)
enroll(\'Adam\', \'M\', 8, city=\'Tianjin\')
enroll(\'Adam\', \'M\', city=\'Tianjin\')     # 当不按顺序提供部分默认参数时,需要把参数名写上。
name: Bob
gender: M
age: 7
city: Beijing

name: Adam
gender: M
age: 8
city: Tianjin

name: Adam
gender: M
age: 6
city: Tianjin

 

  6 参数 - 可变参数

# coding:utf-8

def calc(*nNumbers):        # 可变参数 - 参数前加个*号, 定义tuple参数
    print(type(nNumbers))   # 显示类型
    nSum = 0
    for nLoop in nNumbers:
        nSum = nSum + nLoop
    return nSum


nNums = (1, 2)
nResult = calc(*nNums)  # *nNums : tuple类型  - 作为可变参数
print(nResult)

nNums = [1, 2, 5]
nResult = calc(*nNums)  # *nNums : list类型  - 作为可变参数
print(nResult)
<class \'tuple\'>
3
<class \'tuple\'>
8

 

  7 参数 - 关键字参数

# coding:utf-8
def person(name, age, **kw):
    print("name:", name, "age:", age, "other:", kw)

person("Michael", 30)
person("Bob", 35, city = "BeiJing")
person(age=45, name="Adam", gender=\'M\', job="Engineer") # 用户注册的,除了用户名和年龄是必填,其他都是可选项,

extra = {
    "city": "Beijing",
    "job":"Engineer"}
person("Jack", 24, city=extra["city"], job=extra["job"])
person("Jack", 24, **extra)                                 # 同上简写
name: Michael age: 30 other: {}
name: Bob age: 35 other: {\'city\': \'BeiJing\'}
name: Adam age: 45 other: {\'gender\': \'M\', \'job\': \'Engineer\'}
name: Jack age: 24 other: {\'city\': \'Beijing\', \'job\': \'Engineer\'}
name: Jack age: 24 other: {\'city\': \'Beijing\', \'job\': \'Engineer\'}

 

  8 参数 - 命名关键字参数

# coding:utf-8
def person(name, age, *args, city, job):
    print(\'name:\', name, \'age:\', age, \'city:\', city, \'job:\', job)

person("Bob", 35, city = "BeiJing", job="Engineer")

# 错误用法
# person("Michael", 30)                                   # TypeError: person() missing 2 required keyword-only arguments: \'city\' and \'job\'
# person("Bob", 35, "BeiJing",  "Engineer")                          # TypeError: person() missing 2 required keyword-only arguments: \'city\' and \'job\'
# person(age=45, name="Adam", city = "BeiJing", job="Engineer", gender=\'M\')  # TypeError: person() got an unexpected keyword argument \'gender\'
name: Bob age: 35 city: BeiJing job: Engineer

 

二: 类

  1 定义

# coding:utf-8
class A(object):
    def add(self, a, b):
        return a + b

count = A()
print(count.add(3, 5))
8

 

  2 初始化

# coding:utf-8
class A(object):
    def __init__(self, a, b):
        self.a = int(a)
        self.b = int(b)

    def add(self):
        return self.a + self.b


count = A("4", 5)
print(count.add())
9

 

  3 继承

# coding:utf-8

class A():
    def __init__(self, a, b):
        self.a = int(a)
        self.b = int(b)

    def print(self):
        print("a = %d, b = %d\\n" %(self.a, self.b))


class B(A):
    def sub(self, a, b):
        self.a = self.a - a
        self.b = self.b - b

b = B(4, 5)
b.print()
b.sub(1, 2)
b.print()
a = 4, b = 5

a = 3, b = 3

 

三: 模块

  1 使用模块

# coding:utf-8

import sys

print("\\n\\nPython路径是: ", sys.argv)
Python路径是:  [\'D:/ProgramTools/PyCharm 5.0.4/PycharmProject/StudyJson/StudyJson/Study001.py\']

 

  2 自编模块

# coding:utf-8  # .py文件 - 使用UTF-8编码

"test module"               # 文档注释
__author__ = \'HuaFanChen\'   # 作者名称


def myAbs(nNum):
    if not isinstance(nNum, (int, float)):        # 类型检查
        raise TypeError(\'bad operand type\')    
    if nNum >= 0:
        return nNum
    else:
        return -nNum
        

1 : 编写一个abstest.py文件,内容如上。

 

1 : 把文件放到pyhton库中。

 

# coding:utf-8

from abstest import myAbs

nNum = myAbs(23)
print(nNum)

nNum = myAbs(-33)
print(nNum)
23
33

1 :调用刚才编写abstest文件中的myAbs函数。

 

以上是关于006 python语法_002 函数/类/模块的主要内容,如果未能解决你的问题,请参考以下文章

x006-函数和模块的使用

Python编程之基础知识练习_002

在python中,如何使用unicode内容订购dict?

005 python语法_002

002_Python3基础语法

Python内置函数 __import__ 动态加载模块