python 内置方法 BUILT-IN METHODS

蓝色的 mandelbrot

setattr
getattr
hasattr

1. abs()

returns absolute value of a number 返回绝对值

integer = -20
print('Absolute value of -20 is:', abs(integer))

2. all()

returns true when all elements in iterable is true 都为true则为true

3. any()

Checks if any Element of an Iterable is True 只要有一个为true, 则为true

4. ascii()

Returns String Containing Printable Representation, It escapes the non-ASCII characters in the string using \x, \u or \U escapes.
For example, ö is changed to \xf6n, √ is changed to \u221a

5. bin()

converts integer to binary string 转化为二进制

6. bool() Converts a Value to Boolean

The following values are considered false in Python:

None
False
Zero of any numeric type. For example, 0, 0.0, 0j
Empty sequence. For example, (), [], ''.
Empty mapping. For example, {}
objects of Classes which has bool() or len() method which returns 0 or False

7. bytearray()

returns array of given byte size

8. bytes()

returns immutable bytes object
The bytes() method returns a bytes object which is an immmutable (cannot be modified) sequence of integers in the range 0 <=x < 256.

If you want to use the mutable version, use bytearray() method.

9. callable()

Checks if the Object is Callable

10. chr()

Returns a Character (a string) from an Integer
The chr() method takes a single parameter, an integer i.

The valid range of the integer is from 0 through 1,114,111

11. classmethod()

returns class method for given function
The difference between a static method and a class method is:

Static method knows nothing about the class and just deals with the parameters 静态方法和类无关,仅处理他的参数
Class method works with the class since its parameter is always the class itself. 类方法和类有关但其参数为类本身
类方法的调用可以使用 类名.funcname 或者类的实例 class().funcname

from datetime import date# random Person
class Person:def __init__(self, name, age):self.name = nameself.age = age@classmethoddef fromBirthYear(cls, name, birthYear):return cls(name, date.today().year - birthYear)def display(self):print(self.name + "'s age is: " + str(self.age))person = Person('Adam', 19)
person.display()person1 = Person.fromBirthYear('John',  1985)
person1.display()

12. compile()

The compile() method returns a Python code object from the source (normal string, a byte string, or an AST object
将表达式字符串转化为 python 对象并执行
compile() Parameters
source - a normal string, a byte string, or an AST object
filename - file from which the code was read. If it wasn't read from a file, you can give a name yourself
mode - Either exec or eval or single.
eval - accepts only a single expression.
exec - It can take a code block that has Python statements, class and functions and so on.
single - if it consists of a single interactive statement
flags (optional) and dont_inherit (optional) - controls which future statements affect the compilation of the source. Default Value: 0
optimize (optional) - optimization level of the compiler. Default value -1

13. complex()

Creates a Complex Number 创建复数
z = complex('5-9j')
print(z)
不使用 complex:
a = 2+3j
print('a =',a)
print('Type of a is',type(a))

14. delattr()

Deletes Attribute From the Object 删除某个对象属性

class Coordinate:x = 10y = -5z = 0point1 = Coordinate() print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)delattr(Coordinate, 'z')

15. getattr()

returns value of named attribute of an object,If not found, it returns the default value provided to the function.

class Person:age = 23name = "Adam"person = Person()# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))

16. hasattr()

returns whether object has named attribute

class Person:age = 23name = 'Adam'person = Person()print('Person has age?:', hasattr(person, 'age'))
print('Person has salary?:', hasattr(person, 'salary'))

17. setattr()

sets value of an attribute of object

class Person:name = 'Adam'p = Person()
print('Before modification:', p.name)# setting name to 'John'
setattr(p, 'name', 'John')print('After modification:', p.name)

18. dict()

Creates a Dictionary

empty = dict()
print('empty = ',empty)
print(type(empty))
numbers = dict(x=5, y=0)
print('numbers = ',numbers)
print(type(numbers))
numbers1 = dict({'x': 4, 'y': 5})
print('numbers1 =',numbers1)# you don't need to use dict() in above code
numbers2 = {'x': 4, 'y': 5}
print('numbers2 =',numbers2)# keyword argument is also passed
numbers3 = dict({'x': 4, 'y': 5}, z=8)
print('numbers3 =',numbers3)
# keyword argument is not passed
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)# keyword argument is also passed
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)# zip() creates an iterable in Python 3
numbers3 = dict(zip(['x', 'y', 'z'], [1, 2, 3]))
print('numbers3 =',numbers3)

19. dir()

dir() attempts to return all attributes of this object.

number = [1, 2, 3]
print(dir(number))
# dir() on User-defined Object
class Person:def __dir__(self):return ['age', 'name', 'salary']teacher = Person()
print(dir(teacher))

20. divmod()

Returns a Tuple of Quotient and Remainder 返回商和余数的元组

21. enumerate()

Returns an Enumerate Object
The enumerate() method takes two parameters:

iterable - a sequence, an iterator, or objects that supports iteration
start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start.

grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)print(type(enumerateGrocery))# converting to list
print(list(enumerateGrocery))# changing the default counter
enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))
for count, item in enumerate(grocery, 100):print(count, item)
# 输出
<class 'enumerate'>
[(0, 'bread'), (1, 'milk'), (2, 'butter')]
[(10, 'bread'), (11, 'milk'), (12, 'butter')]
100 bread
101 milk
102 butter

22. eval()

Runs Python Code Within Program

23. exec()

Executes Dynamically Created Program

24. filter()

constructs iterator from elements which are true
filter(function, iterable)
randomList = [1, 'a', 0, False, True, '0']

filteredList = filter(None, randomList) # 返回true的

25. float()

returns floating point number from number, string

26. format()

returns formatted representation of a value
Using format() by overriding format()

class Person:def __format__(self, format):if(format == 'age'):return '23'return 'None'print(format(Person(), "age"))

27. frozenset()

returns immutable frozenset object

28. globals()

returns dictionary of current global symbol table

29. hash()

returns hash value of an object

30. help()

Invokes the built-in Help System

31. hex()

Converts to Integer to Hexadecimal

32. id()

Returns Identify of an Object

33. input()

reads and returns a line of string

34. int()

returns integer from a number or string

35. isinstance()

Checks if a Object is an Instance of Class

36. issubclass()

Checks if a Object is Subclass of a Class

37. iter()

returns iterator for an object

38. len()

Returns Length of an Object

39. list()

creates list in Python

40. locals()

Returns dictionary of a current local symbol table

41. map() Applies Function and Returns a List

42. max() returns largest element

43. memoryview() returns memory view of an argument

44. min() returns smallest element

45. next() Retrieves Next Element from Iterator

46. object() Creates a Featureless Object

47. oct() converts integer to octal

48. open() Returns a File object

49. ord() returns Unicode code point for Unicode character

50. pow() returns x to the power of y

52. property() returns a property attribute

53. range() return sequence of integers between start and stop

54. repr() returns printable representation of an object

55. reversed() returns reversed iterator of a sequence

56. round() rounds a floating point number to ndigits places.

57. set() returns a Python set

58. slice() creates a slice object specified by range()

59. sorted() returns sorted list from a given iterable 不改变原来的, 有返回值

和.sort()的两个不同点:# sort is a method of the list class and can only be used with lists Second, .sort() returns None and modifies the values in place (sort()仅是list的方法,它会改变替换原来的变量)
sorted() takes two three parameters:

iterable - sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator
reverse (Optional) - If true, the sorted list is reversed (or sorted in Descending order)
key (Optional) - function that serves as a key for the sort comparison

# Sort the list using sorted() having a key function
def takeSecond(elem):return elem[1]# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]# sort list with key
sortedList = sorted(random, key=takeSecond)# print list
print('Sorted list:', sortedList)

60. staticmethod() creates static method from a function

61. str() returns informal representation of an object

62. sum() Add items of an Iterable

63. super() Allow you to Refer Parent Class by super

64. tuple() Function Creates a Tuple

65. type() Returns Type of an Object

66. vars() Returns dict attribute of a class

67. zip() Returns an Iterator of Tuples

68. import() Advanced Function Called by import

mathematics = __import__('math', globals(), locals(), [], 0)print(mathematics.fabs(-2.5))
# 等价于
math.fabs(x)

参考文档:https://www.programiz.com/python-programming/methods/built-in/setattr

转载于:https://www.cnblogs.com/bruspawn/p/10823868.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/462657.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

并发与并行的区别

学习多线程的时候会遇到一个名词&#xff1a;并发。这是属于操作系统中的词汇&#xff0c;需要了解并发和并行的区别&#xff0c;从网上搜集了几种说法帮助理解。 一&#xff1a; 并发是指一个处理器同时处理多个任务。 并行是指多个处理器或者是多核的处理器同时处理多个不同的…

Oracle PL/SQL块 多表查询(emp员工表、dept部门表、salgrade工资等级表)

范例: 查询每个员工的编号&#xff0c;姓名&#xff0c;职位&#xff0c;工资&#xff0c;工资等级&#xff0c;部门名称●确定要使用的数据表|- emp表&#xff1a;员工的编号、姓名、职位、工资|- salgrade表&#xff1a;工资等级|- dept表&#xff1a;部门名称●确定已知的关…

多线程的互斥锁应用RAII机制

什么是RAII机制 RAII是Resource Acquisition Is Initialization&#xff08;翻译成 “资源获取即初始化”&#xff09;的简称&#xff0c;是C语言的一种管理资源、避免资源泄漏的惯用法&#xff0c;该方法依赖构造函数资和析构函数的执行机制。 RAII的做法是使用一个类对象&a…

asp.net 浏览服务器文件

http://www.csharpwin.com/dotnetspace/12018r482.shtml 前台文件file.aspx <% Page Language"C#"AutoEventWireup"true"CodeFile"file.aspx.cs"Inherits"file"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transi…

pynput模块—键盘鼠标操作和监听

pynput.mouse&#xff1a;包含控制和监控鼠标或者触摸板的类。 pynput.keyboard&#xff1a;包含控制和监控键盘的类。 上面提到的子包都已被引入到pynput库中。要使用上面的子包&#xff0c;从pynput中引入即可。 下面有详细的示例文档。 控制鼠标 使用pynput.mouse控制鼠标&a…

Windows 恢复环境(Windows RE模式)

Windows 恢复环境 (Windows RE) 是一个能修复无法启动操作系统的常见问题的恢复环境。Windows 预安装环境 (Windows PE) 是具有有限服务的最小 Win32 操作系统。Windows RE 建立在 Windows 预安装环境 (Windows PE) 的基础上&#xff0c;并且可以用附加的驱动程序、语言、Windo…

开源许可证GPL、BSD、MIT、Mozilla、Apache和LGPL的区别

最近工作中遇到了开源许可证的问题&#xff0c;需要测试基于开源软件开发的本公司产品满足哪些开源协议&#xff0c;网上找了一些关于这方面的解答&#xff0c;在此备份下&#xff1a; 首先借用有心人士的一张相当直观清晰的图来划分各种协议&#xff1a;开源许可证GPL、BSD、M…

什么是 mmap

1. mmap 基础概念 mmap 即 memory map&#xff0c;也就是内存映射。 mmap 是一种内存映射文件的方法&#xff0c;即将一个文件或者其它对象映射到进程的地址空间&#xff0c;实现文件磁盘地址和进程虚拟地址空间中一段虚拟地址的一一对映关系。实现这样的映射关系后&#xff…

win10 + 独显 + Anaconda3 + tensorflow_gpu1.13 安装教程(跑bert模型)

这里面有很多坑&#xff0c;最大的坑是发现各方面都装好了结果报错 Loaded runtime CuDNN library: 7.3.1 but source was compiled with: 7.4.1&#xff0c;这是由于最新的tensorflow1.13需要用 Cudnn7.4.1编译。这个问题&#xff0c;StackOverflow上有人问到&#xff0c;但是…

Oracle client 安装、配置

一、安装 链接: https://pan.baidu.com/s/1Yph6hiNkCJsApAzu_Vx2ew 提取码: r9ye 二、配置 1、控制面板\所有控制面板项\管理工具\数据源(ODBC) 注&#xff1a;odbc 分 64 位和 32 位的2、测试 ODBC 连接 Oracle 数据库点击 ODBC&#xff0c;在“用户 DSN”页签下点击添加按钮…

ADO.NET- 基础总结及实例

1、ADO.NET基础介绍 &#xff08;1、程序要和数据库交互要通过ADO.NET进行&#xff0c;通过ADO.NET就能在程序中执行SQL了。ADO.Net中提供了对各种不同数据库的统一操作接口。 (2、直接在项目中内嵌mdf文件的方式使用SQL Server数据库&#xff08;基于服务的数据库&#xff09;…

获取指定日期所属年份的第一天日期或最后一天日期

写了2个自定义函数&#xff0c;获取指定日期所在年份的第一天日期或最后一天的日期&#xff1a; SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- -- Author: Insus.NET -- Create date: 2019-05-09 -- Update date: 2019-05-09 -- Description: 获取指定日期所属年…

高效管理ASP.NET的JavaScript库

简介 对于ASP.NET开发人员来说,管理项目中的JavaScript都很随意&#xff1a; 我想这很大程度上可能是因为网上没有如何妥善处理ASP.NET中JavaScript的可靠信息。此文的目的就是提供一种最佳方案&#xff0c;用于管理ASP.NET中的JavaScript。该方案将能解决以下问题&#xff1a;…

【面试】c++单例模式

1. 单例模式 #include <iostream> using namespace std;class CSingleton { private:CSingleton() {} // 构造是私有的static CSingleton *m_pInstance; public:static CSingleton *GetInstance(){if (m_pInstance NULL) {m_pInstance n…

AIX HACMP集群切换测试实际案例解析

为验证AIX HACMP集群系统的稳定性及保障其上应用的连续性和可靠性&#xff0c;决定周五晚进行集群切换测试。下面是当次过程的文档总结和记录&#xff0c;方便以后参考并备案。系统环境&#xff1a;AIX 5.3数据库&#xff1a; DB2 V8.2存储&#xff1a; IBM DS4700,为两节点配置…

jvm_2

业务线程一直在等待&#xff0c;或者一直在运行&#xff0c;如果不是自己想要的状态&#xff0c;就表明有问题 死锁问题检测 上面程序之所以会死锁&#xff0c;因为下图所示&#xff0c;在-128~127范围内&#xff0c;Integer valueOf后对相同的int值会返回相同的对象&#xff0…

视频播放器

效果图 知识要点 surfaceView.getHolder().setFixedSize(176, 144);//设置分辨率 surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//设置surfaceview不维护自己的缓冲区&#xff0c;而是等待屏幕的渲染引擎将内容推送到用户面前 sur…

前端需要了解的http知识

http基本概念 http是一个无状态 &#xff0c;无连接的基于TCP协议的单向应用层协议 一、无连接 无连接即每次链接只处理一个请求&#xff0c;请求和应答后就断开链接 二、无状态 http的每次请求都是独立的&#xff0c;不相关的&#xff0c;协议对事物处理没有记忆功能。 HTTP无…

局域网中设备的管理之StackCluster

局域网中设备的管理通常采用 stack 、cluster和snmp等方法。 下面我们来讨论一下stack 和cluster。Stack 也叫作堆叠。堆叠是由一些通过堆叠口相连的以太网交换机组成的一个管理域&#xff0c;其中包括一个主交换机和若干个从交换机。堆叠在一起的以太网交换机可以看作为一个设…

3DMed

1. 当前 小论文&#xff0c; before 5.1 2. linux 需要十天的时间&#xff0c; 5月上旬 3. 中下旬写代码&#xff0c;提取算法 。 6月 三维 建模 7月仿真 4. very helpfully , i found this professional open software. Links 3DMed (www.3dmed.net) www.fingerpass.net MOSE…