2021-03-13python学习笔记
1、python函数
1.1 普通函数
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3)
Out[3]: 13
1.2 匿名函数
(lambda x: x > 2)(3)
Out[4]: True
1.3 内建的高阶函数
map(add_10, [1,2,3])
filter(lambda x: x > 5, [3, 4, 5, 6, 7])
# 可以使用列表推导式来模拟 map 和 filter
[add_10(i) for i in [1, 2, 3]]
[x for x in [3, 4, 5, 6, 7] if x > 5]
Out[5]: [6, 7]
2、类 class
def say(self, msg):
return "%s: %s" % (self.name, msg)
# A class method is shared among all instances
# They are called with the calling class as the first argument
# 类方法会被所有实例共享。
# 类方法在调用时,会将类本身作为第一个函数传入。
@classmethod
def get_species(cls):
return cls.species
# A static method is called without a class or instance reference
# 静态方法在调用时,不会传入类或实例的引用。
@staticmethod
def grunt():
return "*grunt*"
3、实例化一个类
class Human(object):
species = "H. sapiens"
def __init__(self, name):
self.name = name
def say(self, msg):
return "%s: %s" % (self.name, msg)
@classmethod
def get_species(cls):
return cls.species
# A static method is called without a class or instance reference
# 静态方法在调用时,不会传入类或实例的引用。
@staticmethod
def grunt():
return "*grunt*"
i = Human(name="Ian")
print (i.say("hi"))
j = Human("Joel")
print (j.say("hello"))
Traceback (most recent call last):
File "<ipython-input-13-ad24899696f4>", line 16, in <module>
print (i.say("hi"))
AttributeError: 'Human' object has no attribute 'say'
- 报错了,具体原因还在查询中
由于这个错误暂时没办法解决,所以之后类相关的基础知识也会报一样的错误,所以今天现到这里,明天再找找报错的原因。