Python打卡Day12
Question 44
Question:
Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).
Hints:
Use map() to generate a list. Use lambda to define anonymous functions.
Main Author's Solution: Python 2
1squaredNumbers = map(lambda x: x**2, range(1,21))
2print squaredNumbers
My Solution: Python 3
1def sqr(x):
2 return x*x
3
4squaredNumbers = list(map(sqr, range(1,21)))
5print (squaredNumbers)
Question 45
Question:
Define a class named American which has a static method called printNationality.
Hints:
Use @staticmethod decorator to define class static method.There are also two more methods.To know more, go to this link.
Main Author's Solution: Python 2
1class American(object):
2 @staticmethod
3 def printNationality():
4 print "America"
5
6anAmerican = American()
7anAmerican.printNationality()
8American.printNationality()
My Solution: Python 3
1class American():
2 @staticmethod
3 def printNationality():
4 print("I am American")
5
6american = American()
7american.printNationality() # this will not run if @staticmethod does not decorates the function.
8 # Because the class has no instance.
9
10American.printNationality() # this will run even though the @staticmethod
11 # does not decorate printNationality()
Question 46
Question:
Define a class named American and its subclass NewYorker.
Hints:
Use class Subclass(ParentClass) to define a subclass.*
Main Author's Solution: Python 2
1class American(object):
2 pass
3
4class NewYorker(American):
5 pass
6
7anAmerican = American()
8aNewYorker = NewYorker()
9print anAmerican
10print aNewYorker
My Solution: Python 3
1class American():
2 pass
3
4class NewYorker(American):
5 pass
6
7american = American()
8newyorker = NewYorker()
9
10print(american)
11print(newyorker)