时间:2022-06-01 11:25:16 | 栏目:Python代码 | 点击:次
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
函数能提高应用的模块性,和代码的重复利用率。你已经知道Python
提供了许多内建函数,比如print()
。但你也可以自己创建函数,这被叫做用户自定义函数。
你可以定义一个由自己想要功能的函数,以下是简单的规则:
def
关键词开头,后接函数标识符名称和圆括号()。return
相当于返回 None。# coding:utf-8 if __name__ == '__main__': ''' 定义:def __init__(self,参数1,参数2......): ...... 使用:在类实例化时触发 类名(参数1,参数2.......) ''' class A(object): def __init__(self, name, sex): print(f'name is {name}, sex is {sex}') a = A('xie', 'man') # name is xie, sex is man
# coding:utf-8 if __name__ == '__main__': ''' 定义: def __getattr(self,属性名) 使用:在访问类不存在的或无权限的属性时触发 object.属性名 ''' class B(object): __name = 'rui' name = 'xie' def __getattr__(self, name): return f'name is {name}' b = B() print(b.name) # xie print(b.__name) # name is __name print(b.sex) # name is sex print(b._B__name) # rui
# coding:utf-8 if __name__ == '__main__': ''' 定义: def __setattr__(self,属性名,属性值) 使用: 给类设置属性值时触发 object.属性名 = 属性值 ''' class C(object): name = '' __name = '' __sex = '' def __setattr__(self, key, value): print(f'I want set key:{key},value:{value}') c = C() c.name = 'xie' # I want set key:name,value:xie c.age = '6666' # I want set key:age,value:6666 c.__sex = 'man' # I want set key:__sex,value:man
# coding:utf-8 if __name__ == '__main__': ''' 定义: def __call__(self,参数1,参数2......) 使用: 把类实例当做函数调用,通过object(参数1,参数2......)触发 ''' class D(object): def __call__(self, *args, **kwargs): print(f'args is {args},kwargs is {kwargs}') d = D() d(*(1, 2, 3), **{'name': 'xie'}) # args is (1, 2, 3),kwargs is {'name': 'xie'}
# coding:utf-8 if __name__ == '__main__': ''' 定义: def __str__(self) 使用: 打印对象时触发 print(object) ''' class F(object): def __str__(self): return '通常用来描述类' f = F() print(f) # 通常用来描述类