今天,是Python认知了解的最后一天,让我们来了解一下Python的(功能)Functions中的方法(def)以及类(classes)
首先来了解一下方法(def)
def sign(x):
if x > 0:
return "positive"
elif x < 0:
return "negative"
else x==0:
return "zero"
for x in [-1,0,1]:
print(sign(x))
# 打印 negative zero positive
我们可以通过定义函数来获取可选的关键字参数
def hello(name, loud = False): #Python中True和Flase的首字母必须大写
if loud:
print("HELLO,%s"%name)
else :
print("Hello,%s"%name)
hello('Bob')
hello('Tom',loud = True)
#打印 Hello Bob HELLO Tom
方法和Java差不多,处理没有返回值类型
接下来,我们来了解一下类(Classes)
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的基础认知,到今天就结束了。简短的六天时间让我对于Python的功能有了很深的认识。
确实是一门很强大的语言。