python 内置方法 BUILT-IN METHODS
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
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.
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()
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
51. print() Prints the Given Object
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
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
總結
以上是生活随笔為你收集整理的python 内置方法 BUILT-IN METHODS的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 批量修改行政区划
- 下一篇: Spring Boot分布式系统实践【扩