2021-03-13python学习笔记

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'
  • 报错了,具体原因还在查询中

由于这个错误暂时没办法解决,所以之后类相关的基础知识也会报一样的错误,所以今天现到这里,明天再找找报错的原因。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值