日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 内置方法 BUILT-IN METHODS

發(fā)布時間:2023/12/20 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 内置方法 BUILT-IN METHODS 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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 轉(zhuǎn)化為二進制

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 靜態(tài)方法和類無關(guān),僅處理他的參數(shù)
Class method works with the class since its parameter is always the class itself. 類方法和類有關(guān)但其參數(shù)為類本身
類方法的調(diào)用可以使用 類名.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
將表達式字符串轉(zhuǎn)化為 python 對象并執(zhí)行
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 創(chuàng)建復(fù)數(shù)
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 返回商和余數(shù)的元組

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

轉(zhuǎn)載于:https://www.cnblogs.com/bruspawn/p/10823868.html

總結(jié)

以上是生活随笔為你收集整理的python 内置方法 BUILT-IN METHODS的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 亚洲中文一区二区三区 | 中文字幕亚洲国产 | 中文有码视频 | 99精品国产一区二区 | 99热这里只有精品在线 | 午夜亚洲av永久无码精品 | 国产情侣av在线 | 水蜜桃91| 久久bb | av一区二区三区四区 | 91丨九色丨蝌蚪丨老版 | 日本日皮视频 | 国产第5页 | 亚洲人女屁股眼交6 | 午夜在线视频免费观看 | 懂色av一区二区三区 | 婷婷av在线 | 激情婷婷在线 | 国产精品99久久久久久久女警 | 欧美性猛交xxxx黑人猛交 | 美国做爰xxxⅹ性视频 | 哪里可以看毛片 | 国产高清免费在线 | 国产做爰免费观看视频 | 女同毛片一区二区三区 | 亚洲风情第一页 | 精品一区二区人妻 | 歪歪视频在线观看 | 五月天婷婷在线视频 | 加勒比视频在线观看 | 在线播放不卡 | 久久老女人 | 日本久久99 | 久久亚洲精品小早川怜子 | 亚洲成人精品在线播放 | 日本做爰高潮又黄又爽 | 国产精选在线 | 伊人青青草原 | ts人妖另类精品视频系列 | 韩国三级一区 | 青青草久 | 色婷婷基地 | 四季av一区二区凹凸精品 | 国产123区| 欧美黄色录像带 | 欧美性猛交xxxx黑人猛交 | 性久久久| 黑人添美女bbb添高潮了 | 国产一区在线观看免费 | 蜜臀av一区 | 欧美一区二区日韩一区二区 | 严厉高冷老师动漫播放 | 国产av一区二区三区 | 越南av| 成人福利在线视频 | 神马久久午夜 | 在线观看91av| 欧美无砖专区免费 | 操碰在线视频 | 黄色免费一级片 | a级大片免费看 | 一级国产黄色片 | 91正在播放 | 国产精品自拍合集 | 91大神在线观看视频 | 日韩精品在线观看一区 | 激情999 | 国产精品成人网 | 一区二区高清在线观看 | 一区二区三区不卡视频在线观看 | 波多野结衣91 | 成人教育av在线 | 性高跟鞋xxxxhd国产电影 | 熟女人妻aⅴ一区二区三区60路 | 欧美综合一区二区 | 婷婷亚洲综合五月天小说 | 熟女俱乐部一区二区 | 18深夜在线观看免费视频 | 亚洲少妇第一页 | 中文字幕在线视频日韩 | 国产一区二区三区精品愉拍 | 天天躁日日躁狠狠躁 | 亚洲色图一区二区 | 伊人毛片 | 国产又黄又粗又硬 | 亚洲最新 | 色性网站 | 豆花视频在线 | 国产精品久久久久一区二区三区 | 欧美乱大交xxxxx潮喷l头像 | 日本三级456 | 一级黄片毛片 | 国产白浆一区二区 | 热久久精品免费视频 | 亚洲精品另类 | 囯产精品久久久久久 | 澳门久久 | 五月婷婷视频在线 | 国产精品美女久久久久 |