python 中的函数与类

2025-10-06 19:13:30

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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢