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

from datetime import date

# random Person
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def 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 = 10
  y = -5
  z = 0

point1 = 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 = 23
    name = "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 = 23
    name = '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 不改变原来的

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

猜你喜欢

转载自www.cnblogs.com/bruspawn/p/10823868.html