phython——函数、Lambda 表达式、类与对象、魔法方法

一、函数

1. 定义:
def functionname (parameters):
       "函数文档字符串"
        functionsuite
        return [expression]

2. 调用:
def printme(str):
    print(str)
printme('hello')

3. 函数参数
#位置参数
def functionname(arg1):
       "函数文档字符串"
       functionsuite
       return [expression]
       
#默认参数,默认参数一定要放在位置参数 后面,不然程序会报错
def functionname(arg1, arg2=v):
       "函数文档字符串"
       functionsuite
       return [expression]

#可变参数,传入的参数个数是可变的
def printinfo(arg1, *args):
    print(arg1)
    for var in args:
        print(var)
printinfo(10)  # 10
printinfo(70, 60, 50)

#关键字参数,**kwargs
#可变参数允许传入零个到任意个参数,它们在函数调用时自动组装为一个元组 (tuple)。
#关键字参数允许传入零个到任意个参数,它们在函数内部自动组装为一个字典 (dict)。
def printinfo(arg1, *args, **kwargs):
    print(arg1)
    print(args)
    print(kwargs)
printinfo(70, 60, 50)
# 70
# (60, 50)
# {}
printinfo(70, 60, 50, a=1, b=2)
# 70
# (60, 50)
# {'a': 1, 'b': 2}

#命名关键字参数(*, nkw),如果要限制关键字参数的名字,就可以用「命名关键字参数」
def printinfo(arg1, *, nkw, **kwargs):
    print(arg1)
    print(nkw)
    print(kwargs)
printinfo(70, nkw=10, a=1, b=2)
# 70
# 10
# {'a': 1, 'b': 2}

参数定义的顺序必须是:
位置参数、默认参数、可变参数和关键字参数。
位置参数、默认参数、命名关键字参数和关键字参数。

4. 变量作用域
#当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字。
#global关键字用来在函数或其他局部作用域中使用全局变量。但是如果只访问不修改全局变量则不需要使用global关键字
#nonlocal声明的变量不是局部变量,也不是全局变量,而是外部嵌套函数内的变量
num = 1
def fun1():
    global num  # 需要使用 global 关键字声明
    print(num)  # 1
    num = 123
    print(num)  # 123
fun1()
print(num)  # 123

二、Lambda 表达式

用 lambda 关键词定义的匿名函数

语法结构:
lambda argument_list: expression
lambda - 定义匿名函数的关键词。
argument_list - 函数参数,它们可以是位置参数、默认参数、关键字参数,和正规函数里的参数类型一样。
expression - 只是一个表达式,输入函数参数,输出一些值。

#因为 lambda 不需要它来返回,表达式本身结果就是返回值。
lbd_sqr = lambda x: x ** 2

三、类与对象

1. 定义和使用:
class Turtle:  # Python中的类名约定以大写字母开头
    """关于类的一个简单例子"""
    # 属性
    color = 'green'
    weight = 10
    legs = 4
    shell = True
    mouth = '大嘴'

    # 方法
    def climb(self):
        print('我正在很努力的向前爬...')

    def run(self):
        print('我正在飞快的向前跑...')

    def bite(self):
        print('咬死你咬死你!!')

    def eat(self):
        print('有得吃,真满足...')

    def sleep(self):
        print('困了,睡了,晚安,zzz')
tt = Turtle()
print(tt)
# <__main__.Turtle object at 0x0000007C32D67F98>

print(type(tt))
# <class '__main__.Turtle'>

print(tt.__class__)
# <class '__main__.Turtle'>

print(tt.__class__.__name__)
# Turtle

tt.climb()
# 我正在很努力的向前爬...

tt.run()
# 我正在飞快的向前跑...

tt.bite()
# 咬死你咬死你!!

# Python类也是对象。它们是type的实例
print(type(Turtle))
# <class 'type'>

2. self 
#Python 的 self 相当于 C++ 的 this 指针。
class Test:
    def prt(self):
        print(self)
        print(self.__class__)
t = Test()
t.prt()
# <__main__.Test object at 0x000000BC5A351208>
# <class '__main__.Test'>

3.Python 的魔法方法
__init__(self[, param1, param2...])  #	该方法在类实例化时会自动调用。
class Ball:
    def __init__(self, name):
        self.name = name
4. 公有和私有
#在 Python 中定义私有变量只需要在变量名或函数名前加上“__”两个下划线,那么这个函数或变量就会为私有的了。
class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0  # 公开变量
	def __foo(self):  # 私有方法
        print('这是私有方法')

5. 继承
class BaseClassName(基类名):
	xxx
#如果子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法或属性。

6.魔法方法
__del__(self) #析构器,当一个对象将要被系统回收之时调用的方法。
class C(object):
    def __init__(self):
        print('into C __init__')

    def __del__(self):
        print('into C __del__')

__add__(self, other) #定义加法的行为:+
__sub__(self, other) #定义减法的行为:-
class MyClass:

    def __init__(self, height, weight):
        self.height = height
        self.weight = weight

    # 两个对象的长相加,宽不变.返回一个新的类
    def __add__(self, others):
        return MyClass(self.height + others.height, self.weight + others.weight)

    # 两个对象的宽相减,长不变.返回一个新的类
    def __sub__(self, others):
        return MyClass(self.height - others.height, self.weight - others.weight)

    # 说一下自己的参数
    def intro(self):
        print("高为", self.height, " 重为", self.weight)

__mul__(self, other) #定义乘法的行为:*
__truediv__(self, other) #定义真除法的行为:/
__floordiv__(self, other) #定义整数除法的行为://
__mod__(self, other) #定义取模算法的行为:%
__pow__(self, other[, module]) #定义当被 power() 调用或 ** 运算时的行为
__lshift__(self, other) #定义按位左移位的行为:<<
__rshift__(self, other) # 定义按位右移位的行为:>>
__and__(self, other) #定义按位与操作的行为:&
__xor__(self, other) #定义按位异或操作的行为:^
__or__(self, other) #定义按位或操作的行为:|
__iadd__(self, other) #定义赋值加法的行为:+=
__isub__(self, other) #定义赋值减法的行为:-=
__imul__(self, other) #定义赋值乘法的行为:*=
__itruediv__(self, other) #定义赋值真除法的行为:/=
__ifloordiv__(self, other) #定义赋值整数除法的行为://=
__imod__(self, other) #定义赋值取模算法的行为:%=
__ipow__(self, other[, modulo]) #定义赋值幂运算的行为:**=
__ilshift__(self, other) #定义赋值按位左移位的行为:<<=
__irshift__(self, other) #定义赋值按位右移位的行为:>>=
__iand__(self, other) #定义赋值按位与操作的行为:&=
__ixor__(self, other) #定义赋值按位异或操作的行为:^=
__ior__(self, other) #定义赋值按位或操作的行为:|=

__getattr__(self, name): #定义当用户试图获取一个不存在的属性时的行为。
__getattribute__(self, name)#定义当该类的属性被访问时的行为(先调用该方法,查看是否存在该属性,若不存在,接着去调用__getattr__)。
__setattr__(self, name, value)#定义当一个属性被设置时的行为。
__delattr__(self, name)#定义当一个属性被删除时的行为。

__get__(self, instance, owner) #用于访问属性,它返回属性的值。
__set__(self, instance, value) #将在属性分配操作中调用,不返回任何内容。
__del__(self, instance) #控制删除操作,不返回任何内容。
.........

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值