Python参数类型定义、私有函数与变量、全局变量

文章介绍了Python3.7后引入的函数参数类型定义,展示了如何定义带默认值和可变参数的函数。同时,解释了类中的私有函数和私有变量的概念及定义方式。此外,讨论了全局变量和局部变量的使用,并提到了`global`关键字在修改全局变量时的作用。最后,举例说明了如何在函数内部操作列表和字典等数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

函数的参数类型定义

  • 参数名 + 冒号 + 类型函数
  • 函数定义在Python3.7之后可用
  • 函数不会对参数类型进行验证
  • def add(a:int, b:int=3):
        print(a + b)
    
    add(1, 2)
    add('hello', 'xiaomu')
    
    def test(a:int, b:int=3, *args:int, **kwargs):
        print(a, b, args, kwargs)
    
    test(1, 2, 3, '4', name='xiaomu')
    
    def test2(a:int, b, c=3):
        print(a, b, c)
    
    test2(1, 3, 4)

类中的私有函数与私有变量 

1、什么是私有函数私有变量

  • 无法被实例化后的对象调用的类中的函数与变量
  • 类内部可以调用私有函数与变量
  • 只希望类内部业务调用使用,不希望被使用者调用

2、私有函数与私有变量的定义

  • 在变量或函数前添加__(2个下横线),变量或函数名后面无需添加
  • # coding : utf-8
    
    class Cat(object):
        __cat_type = 'cat'
    
        def __init__(self, name, sex):
            self.name = name
            self.__sex = sex
    
        def run(self):
            result = self.__run()
            print(result)
    
        def __run(self):
            return f'{self.__cat_type} little cat {self.name} {self.__sex} is running happyly'
    
        def jump(self):
            result = self.__jump()
            print(result)
    
        def __jump(self):
            return f'{self.__cat_type} little cat {self.name} {self.__sex} is jumping happyly'
    
    class Test(object):
        pass
    
    cat = Cat(name='rice', sex='boy')
    cat.run()
    cat.jump()
    print(dir(cat))
    print(cat._Cat__jump())
    print(cat._Cat__cat_type)

局部变量与全局变量 

1、全局变量

  • 在Python脚本最上层代码块的变量
  • 全局变量可以在函数内被读取使用
  • # coding : utf-8
    
    name = 'dewei'
    
    def test():
        print(name)
    
    test()
    
    def test1():
        name = 'xiaomu'
        print('in the def', name)
    
    test1()
    print('out the def', name)

2、局部变量

def test3():
    age = 33
    print(age)

test3()

def test4(a):
    a = 10

3、global

  • 将全局变量可以在函数体内进行修改
  • 列表和字典的全局变量并不需要global声明
  • def test5():
        global name
        global age
        name = 10
        age = 18
    
    test5()
    print(name)
    print(age)
    
    test_dict = {'a' : 1, 'b' : 2}
    
    def test6():
        test_dict['c'] = 3
        test_dict.pop('a')
    
    test6()
    print(test_dict)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Win_77

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值