python 中的函数与类

 时间:2026-05-08 17:03:13

1、在python中常常使用def关键字来定义一个函数 。注意缩进。

举个例子:

def sign(x):

    if x > 0:

        return 'positive'

    elif x < 0:

        return 'negative'

    else:

        return 'zero'

for x in [-1, 0, 1]:

    print(sign(x))

# Prints "negative", "zero", "positive"

python 中的函数与类

2、输出结果如下 :

negative

zero

positive

python 中的函数与类

3、在定义函数的时候我们也可以缺省一些参数。

举个例子:

def hello(name, loud=False):

    if loud:

        print('HELLO, %s!' % name.upper())

    else:

        print('Hello, %s' % name)

hello('Bob') # Prints "Hello, Bob"

hello('Fred', loud=True)  # Prints "HELLO, FRED!"

python 中的函数与类

4、运行结果如下:

Hello, Bob

HELLO, FRED!

python 中的函数与类

5、python定义类的方式也非常直接。

class Greeter(object):

    # Constructor

    def __init__(self, name):

        self.name = name  # Create an instance variable

    # Instance method

    def greet(self, loud=False):

        if loud:

            print('HELLO, %s!' % self.name.upper())

        else:

            print('Hello, %s' % self.name)

g = Greeter('Fred')  # Construct an instance of the Greeter class

g.greet()            # Call an instance method; prints "Hello, Fred"

g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"

python 中的函数与类

6、运行结果如下:

Hello, Fred

HELLO, FRED!

python 中的函数与类

  • 如何开启申万宏源大笔卖出
  • 额头长痘痘怎么快速去除
  • 2345安全卫士如何添加弹窗广告到拦截列表中
  • 可以在微信制作外卖小程序吗—外卖小程序优势
  • 惊奇队长如何打败灭霸
  • 热门搜索
    generation是什么意思 办社保卡需要什么资料 锦鲤养殖 weirdo什么意思 电磁炉什么牌子好 黑五类是什么 什么是刷机 量贩式ktv是什么意思 任重道远是什么意思 红颜知己是什么