当前位置:实例文章 » Python实例» [文章]Python参数类型定义、私有函数与变量、全局变量

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

发布人:shili8 发布时间:2023-03-26 04:19 阅读次数:13

?

函数的参数类型定义

  • 参数名 + 冒号 + 类型函数
  • 函数定义在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)

相关标签:

免责声明

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱290110527@qq.com删除。

其他信息

其他资源

Top