网站首页 美食营养 游戏数码 手工爱好 生活家居 健康养生 运动户外 职场理财 情感交际 母婴教育 时尚美容

python 中的函数与类

时间:2024-10-20 04:41:03

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、输出结果如下 :negativezeropositive

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, BobHELLO, 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 classg.greet() # Call an instance method; prints "Hello, Fred"g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"

python 中的函数与类

6、运行结果如下:Hello, FredHELLO, FRED!

python 中的函数与类
© 2025 五度知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com