5、python基础语法——方法和函数

本文探讨了Python中方法与函数的区别。函数是独立的功能,而方法与对象相关联,如`type()`函数和字符串的`upper()`方法。每个数据类型都有其内置的函数和方法,可以通过`dir()`函数查看。例如,`str`和`int`类型拥有各自的属性和操作方法。
摘要由CSDN通过智能技术生成

在 Python 中,方法(Method)和函数(Function)是可以互换的两个词,它们之间有一个细微的区别:函数是独立的功能,无须与对象关联。方法则与对象有关,不需要传递数据或参数就可以使用。
举例如下:
type就是一个函数,

>>> a=123
>>> type(a)
<class 'int'>

方法需要与一个对象(变量或数据)关联,比如 upper()是一个方法,它的作用是将字符串内容里小写的英文字母转换为大写的英文字母,代码如下:


>>> network=("cisco")
>>> network.upper()
'CISCO'

在 Python 中,每种数据类型都有自己默认自带的函数、方法和变量,要查看某一数据类型本身具有的函数、方法和变量,可以使用 dir()函数,这里以字符串和整数为例:

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
 '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
 '__getitem__', '__getnewargs__', '__gt__', '__hash__', 
 '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', 
 '__lt__', '__mod__', '__mul__', '__ne__', '__new__', 
 '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', 
 '__rmul__', '__setattr__', '__sizeof__', '__str__', 
 '__subclasshook__', 'capitalize', 'casefold', 'center', 'count',
 'encode', 'endswith', 'expandtabs', 'find', 'format',
 'format_map', 'index', 'isalnum', 'isalpha', 'isascii',
 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
 'translate', 'upper', 'zfill']

```python

>>> dir(int)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', 
'__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', 
'__eq__', '__float__', '__floor__', '__floordiv__', '__format__', 
'__ge__', '__getattribute__', '__getnewargs__', '__gt__', 
'__hash__', '__index__', '__init__', '__init_subclass__', 
'__int__', '__invert__', '__le__', '__lshift__', '__lt__', 
'__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', 
'__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', 
'__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__',
'__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', 
'__rpow__', '__rrshift__', '__rshift__', '__rsub__', 
'__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', 
'__str__', '__sub__', '__subclasshook__', '__truediv__', 
'__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 
'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 
'real', 'to_bytes']
>>>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值