python 中的函数与类

时间:2026-02-14 14:35:48

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 中的函数与类

© 2026 海能知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com