SlideShare a Scribd company logo
파이썬 내장 함수
정보기술 시대에 유익한 파이썬 프로그래밍 – 제 6 강 (2)
동양미래대학교
2015.7
최용 <sk8er.choi@gmail.com>
내장 함수
Built-in Functions
Python3 내장 함수
Built-in Functi
ons
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
delattr() hash() memoryview() set()
https://docs.python.org/3/library/functions.html
abs()
>>> abs(-3)
3
>>> abs(-3.0)
3.0
>>> z = complex(1, 2)
>>> abs(z)
2.23606797749979
all()
>>> all([True, True, True])
True
>>> all([True, False, True])
False
any()
>>> any([True, False, True])
True
>>> any((False, False, False))
False
ascii()
>>> ascii('''Airbed
... Breakfast''')
"'AirbednBreakfast'"
>>> ascii('김치')
"'uae40uce58'"
bin()
>>> bin(1)
'0b1'
>>> bin(2)
'0b10'
>>> bin(3)
'0b11'
>>> bin(4)
'0b100'
bool()
>>> bool(True)
True
>>> bool(2 < 3)
True
>>> bool(1)
True
>>> bool(3 % 2)
True
>>> bool(not None)
True
>>> bool(False)
False
>>> bool(2 > 3)
False
>>> bool(0)
False
>>> bool(4 % 2)
False
>>> bool(None)
False
>>> bool()
False
bytearray()
>>> data = bytearray(b'Monty Python')
>>> data[5] = 33 # mutable
>>> data
bytearray(b'Monty!Python')
http://python3porting.com/problems.html#manipulating-binary-data
http://dabeaz.blogspot.kr/2010/01/few-useful-bytearray-tricks.html
bytes()
>>> b'Python'
b'Python'
>>> type(b'Python')
<class 'bytes'>
>>> b'파이썬'
File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
>>> bytes('Python', 'utf-8')
b'Python'
>>> bytes('파이썬', 'utf-8')
b'xedx8cx8cxecx9dxb4xecx8dxac'
callable()
>>> def sum(x, y):
... return x + y
...
>>> callable(sum)
True
>>> x = 10
>>> callable(x)
False
>>> class MyClass:
... pass
...
>>> callable(MyClass)
True
>>> obj = MyClass()
>>> callable(obj)
False
http://joequery.me/code/python-builtin-functions/#callable
chr()
>>> chr(65)
'A'
>>> chr(97)
'a'
>>> chr(49)
'1'
classmethod()
>>> class Pizza:
... radius = 42
... @classmethod
... def get_radius(cls):
... return cls.radius
...
>>> Pizza.get_radius()
42
https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods
compile()
>>> codeobj = compile('x = 2nprint("X is " + str(x))', # source
... 'fakemodule', # file name
... 'exec') # mode
>>> exec(codeobj)
X is 2
http://stackoverflow.com/questions/22443939/python-built-in-function-compile-what-is-it-used-for
complex()
>>> x = complex("4+2j")
>>> x
(4+2j)
>>> y = complex("4-5j")
>>> y
(4-5j)
>>> x+y
(8-3j)
>>> x*y
(26-12j)
>>> complex("4")
(4+0j) http://joequery.me/code/python-builtin-functions/#complex
delattr()
>>> class Employee:
... def __init__(self, name, salary):
... self.name = name
... self.salary = salary
...
>>> j = Employee("John", "2000$")
>>> j.salary
'2000$'
>>> delattr(j, "salary")
>>> hasattr(j, "salary")
False
dict()
>>> dict()
{}
>>> dict( [[1, 'a'], [2, 'b'], [3, 'c']] )
{1: 'a', 2: 'b', 3: 'c'}
>>> dict( ((1, 'a'), (2, 'b'), (3, 'c')) )
{1: 'a', 2: 'b', 3: 'c'}
dir()
>>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
...
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
>>> import struct
>>> dir(struct)
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__pack
age__', '__spec__', '_clearcache', 'calcsize', 'error', 'iter_unpack', 'pack', 'pack_into', 'unpack', 'unpack_
from']
divmod()
>>> divmod(7, 3)
(2, 1)
>>> divmod(8.4, 4.2)
(2.0, 0.0)
>>> divmod(8.5, 4.2)
(2.0, 0.09999999999999964)
enumerate()
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
eval()
>>> x = 1
>>> eval('x + 1')
2
>>> y = eval('x + 2')
>>> y
3
>>> a = 10
>>> b = 5
>>> D = {'a': 2, 'b': 3}
>>> eval('a + b')
15
>>> eval('a + b', D)
5
exec()
>>> a = 3
>>> exec('b = 2') # eval()과 달리, 값을 리턴하지 않음
>>> exec('c = a + b')
>>> c
5
filter()
>>> N = range(1, 11)
>>> Even = list()
>>> for n in N:
... if n % 2 == 0:
... Even.append(n)
...
>>> Even
[2, 4, 6, 8, 10]
>>> Odd = list(filter(lambda x: x % 2, N))
>>> Odd
[1, 3, 5, 7, 9]
float()
>>> float(1)
1.0
>>> float(1.234)
1.234
>>> float('+1.23')
1.23
>>> float(' -12345n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf
format()
>>> L = [['a', 123], ['by', 45.6], ['cow', 7.89]]
>>> for s, n in L:
... print(s, n)
...
a 123
by 45.6
cow 7.89
>>> for s, n in L:
... print(format(s, '^10') + '|' + format(n, '<.2f'))
...
a |123.00
by |45.60
cow |7.89 http://joequery.me/code/python-builtin-functions/#format
frozenset()
set
• mutable
• add()
• remove()
frozenset
• immutable: 생성된 이후에는
내용을 변경할 수 없음
getattr()
>>> class MyClass:
... x = 0
... y = 1
...
>>> myobj = MyClass()
>>> getattr(myobj, 'x')
0
globals()
>>> globals()
{'__name__': '__main__', '__builtins__': <module
'builtins' (built-in)>, '__loader__': <class '_frozen_
importlib.BuiltinImporter'>, '__spec__': None, '__
doc__': None, '__package__': None}
>>> balance = 200
>>> cost = 50
>>> globals()
{'__name__': '__main__', '__builtins__': <module
'builtins' (built-in)>, 'balance': 200, '__loader__': <
class '_frozen_importlib.BuiltinImporter'>, '__spe
c__': None, '__doc__': None, '__package__': Non
e, 'cost': 50}
>>> eval('balance - cost')
150
>>> mylocals = {'cost': 75}
>>> eval('balance - cost', mylocals)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'balance' is not defined
>>> eval('balance - cost', globals(), mylocals)
125
http://joequery.me/code/python-builtin-functions/#eval
hasattr()
>>> class MyClass:
... x = 0
... y = 1
...
>>> myobj = MyClass()
>>> hasattr(myobj, 'y')
True
>>> hasattr(myobj, 'z')
False
hash()
>>> hash('One little, two little, three little indians')
-7814896826006998464
>>> hash('indian')
-8497506485016990678
>>> hash('boy')
2674027540618413217
>>> hash('One little, two little, three little indians')
-7814896826006998464
>>> hash('indian')
-8497506485016990678
http://stackoverflow.com/questions/7646520/is-this-an-appropriate-use-of-pythons-built-in-hash-function
http://www.pythoncentral.io/hashing-strings-with-python/
help()
>>> help(eval)
Help on built-in function eval in module builtins:
eval(...)
eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
hex()
>>> for n in range(20):
... print(hex(n))
...
0x0
0x1
0x2
0x3
0x4
0x5
0x6
0x7
0x8
0x9
0xa
0xb
0xc
0xd
0xe
0xf
0x10
0x11
0x12
0x13
id()
>>> a = 1
>>> b = 2
>>> L = [a, b]
>>> M = L
>>> id(L[0])
4297370688
>>> id(M[0])
4297370688
input()
>>> s = input('Type any string: ')
Type any string: Python
>>> print(s)
Python
int()
>>> n = int(input('Type any number: '))
Type any number: 3
>>> print(n * n)
9
isinstance()
>>> class Human:
... pass
...
>>> me = Human()
>>> isinstance(me, Human)
True
>>> class Robot:
... pass
...
>>> you = Robot()
>>> isinstance(you, Human)
False
>>> class Vehicle:
... pass
...
>>> class Car(Vehicle):
... pass
...
>>> mycar = Car()
>>> isinstance(mycar, Car)
True
>>> isinstance(mycar, Vehicle)
True
issubclass()
>>> class Vehicle:
... pass
...
>>> class Car(Vehicle):
... pass
...
>>> issubclass(Car, Vehicle)
True
iter()
>>> my_list = [5, 1, 6, 3]
>>> my_iter = iter(my_list)
>>> next(my_iter)
5
>>> next(my_iter)
1
>>> next(my_iter)
6
>>> next(my_iter)
3
len()
>>> len('Python')
6
>>> len('파이썬')
3
>>> len([2, 3, 6, 4, 5, 20])
6
list()
>>> list([1, 2, 3])
[1, 2, 3]
>>> list((1, 2, 3))
[1, 2, 3]
>>> list('XYZxyz')
['X', 'Y', 'Z', 'x', 'y', 'z']
locals()
>>> def foo(arg): # 함수 foo는 로컬 네임스페이스에 두 개의 변수 arg와 x를 가짐
... x = 1
... print(locals())
...
>>> foo(7) # locals는 이름/값 사전을 리턴
{'x': 1, 'arg': 7}
>>> foo('bar')
{'x': 1, 'arg': 'bar'}
http://www.diveintopython.net/html_processing/locals_and_globals.html
map()
for … in …
>>> M = list()
>>> for x in range(1, 6):
... M.append(x % 2)
...
>>> M
[1, 0, 1, 0, 1]
map()
>>> map(lambda x: x % 2, range(1, 6))
<map object at 0x101a67d30>
>>> list(_)
[1, 0, 1, 0, 1]
max()
>>> max(1234, 234, 34, 4)
1234
>>> max([3, 9, 27])
27
>>> max('return')
'u'
memoryview()
>>> ba = bytearray(b'abcdefgh')
>>> mv = memoryview(ba)
>>> mv[4:6]
<memory at 0x0000000002BB7CC8>
>>> mv[4:6].tobytes()
b'ef'
>>> mv[4:6] = b'ZA'
>>> ba
bytearray(b'abcdZAgh')
http://eli.thegreenplace.net/2011/11/28/less-copies-in-python-with-the-buffer-protocol-and-memoryviews
min()
>>> min(1234, 234, 34, 4)
4
>>> min('invest')
'e'
next()
>>> my_list = [5, 1, 6, 3]
>>> my_iter = iter(my_list)
>>> next(my_iter)
5
>>> next(my_iter)
1
>>> next(my_iter)
6
>>> next(my_iter)
3
object()
>>> obj = object()
>>> type(obj)
<class 'object'>
oct()
>>> for n in range(1, 21):
... print(str(n) + ': ' + oc
t(n))
...
1: 0o1
2: 0o2
3: 0o3
4: 0o4
5: 0o5
6: 0o6
7: 0o7
8: 0o10
9: 0o11
10: 0o12
11: 0o13
12: 0o14
13: 0o15
14: 0o16
15: 0o17
16: 0o20
17: 0o21
18: 0o22
19: 0o23
20: 0o24
open()
>>> with open("test.txt", "wt") as out_file:
... out_file.write("This Text is going to out filenLook at it
and see!")
...
50
>>> with open("test.txt", "rt") as in_file:
... text = in_file.read()
...
>>> print(text)
This Text is going to out file
Look at it and see!
https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/File_IO
ord()
>>> ord('A')
65
>>> ord('a')
97
>>> ord('1')
49
pow()
>>> pow(2, 5)
32
print()
>>> print('Python 3.4')
Python 3.4
>>> print('Python', '3.4')
Python 3.4
>>> print('Python', '3.4', sep='
')
Python 3.4
>>> print('Python', '3.4', sep='
_')
Python_3.4
>>> for x in range(3):
... print(x, end='n')
...
0
1
2
>>> for x in range(3):
... print(x, end='t')
...
0 1 2 >>>
property()
class C:
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x'
property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
>>> c = C()
>>> c.x = 10
>>> print(c.x)
10
>>> del c.x
>>> help(C)
Help on class C in module __main__:
class C(builtins.object)
| Methods defined here:
|
| __init__(self)
|
| -----------------------------------------------------------
-----------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| x
| I'm the 'x' property.
range()
>>> range(10)
range(0, 10)
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> tuple(range(5))
(0, 1, 2, 3, 4)
>>> for x in range(0, 10, 2):
... print(x)
...
0
2
4
6
8
>>> for y in range(10, 0, -1):
... print(y)
...
10
9
8
7
6
5
4
3
2
1
repr()
>>> repr('''Airbed
... Breakfast''')
"'AirbednBreakfast'"
>>> repr('김치')
"'김치'"
reversed()
>>> reversed([0, 1, 2, 3, 4])
<list_reverseiterator object at 0x101a67c50>
>>> list(reversed([0, 1, 2, 3, 4]))
[4, 3, 2, 1, 0]
round()
>>> round(3.1415)
3
>>> round(3.1415, 2)
3.14
set()
>>> A = set([n for n in range(2, 31, 2)])
>>> 4 in A
True
>>> len(A)
15
>>> A.add(32)
>>> A
{32, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26,
28, 30}
>>> {4, 8, 12}.issubset(A)
True
>>> {4, 8, 12} < A
True
>>> B = set([n for n in range(3, 31,
3)])
>>> C = A.intersection(B)
>>> C
{24, 18, 12, 6, 30}
>>> A.issuperset(C)
True
>>> sorted(C)
[6, 12, 18, 24, 30]
>>> D = A.union(B)
>>> D
{2, 3, 4, 6, 8, 9, 10, 12, 14, 15,
16, 18, 20, 21, 22, 24, 26, 27, 28,
30}
setattr()
>>> class Employee:
... def __init__(self, name, salary):
... self.name = name
... self.salary = salary
...
>>> j = Employee("John", "2000$")
>>> j.salary
'2000$'
>>> setattr(j, "salary", "3000$")
>>> j.salary
'3000$'
>>> setattr(j, "gender", "male")
>>> j.gender
'male'
slice()
>>> L = [0, 1, 2, 3, 4, 5, 6, 7,
8, 9]
>>> L[2:7]
[2, 3, 4, 5, 6]
>>> L[2:7:2]
[2, 4, 6]
>>> s = slice(2, 7)
>>> L[s]
[2, 3, 4, 5, 6]
>>> s = slice(2, 7, 2)
>>> L[s]
[2, 4, 6]
sorted()
>>> sorted([2, 3, 6, 4, 5, 20])
[2, 3, 4, 5, 6, 20]
staticmethod()
>>> class Util:
... @staticmethod
... def add(a, b):
... return a + b
...
>>> Util.add(2, 3)
5
http://pyengine.blogspot.kr/2011/08/staticmethod-vs-classmethod.html
str()
>>> str(1)
'1'
>>> str('a')
'a'
>>> str([1, 'a'])
"[1, 'a']"
>>> str(None)
'None'
sum()
>>> sum([3, 9, 27])
39
super()
class LoggingDict(dict):
def __setitem__(self, key, value):
logging.info('Settingto %r' % (key, value))
super().__setitem__(key, value)
https://rhettinger.wordpress.com/2011/05/26/super-considered-super/
tuple()
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> tuple((1, 2, 3))
(1, 2, 3)
>>> tuple('XYZxyz')
('X', 'Y', 'Z', 'x', 'y', 'z')
type()
>>> type(2)
<class 'int'>
>>> type('boy')
<class 'str'>
>>> type([2, 'boy'])
<class 'list'>
>>> type(None)
<class 'NoneType'>
>>> import calendar
>>> type(calendar)
<class 'module'>
>>> class MyClass:
... pass
...
>>> mc = MyClass()
>>> type(mc)
<class '__main__.MyClass'>
vars()
>>> class Employee:
... def __init__(self, name, salary):
... self.name = name
... self._salary = salary
...
...
>>> j = Employee("John", "2000$")
>>> vars(j)
{'name': 'John', '_salary': '2000$'}
zip()
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> list(zipped)
[]
__import__()
>>> from math import pi
>>> pi
3.141592653589793
>>> _temp = __import__('math', globals(), locals(), ['pi'], 0)
>>> pi = _temp.pi
>>> pi
3.141592653589793

More Related Content

PDF
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
PDF
Python Programming: Data Structure
Chan Shik Lim
 
PDF
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
Masashi Shibata
 
PDF
Introducción a Elixir
Svet Ivantchev
 
PDF
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 
PDF
Palestra sobre Collections com Python
pugpe
 
KEY
Haskellで学ぶ関数型言語
ikdysfm
 
PDF
Python dictionary : past, present, future
delimitry
 
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
Python Programming: Data Structure
Chan Shik Lim
 
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
Masashi Shibata
 
Introducción a Elixir
Svet Ivantchev
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 
Palestra sobre Collections com Python
pugpe
 
Haskellで学ぶ関数型言語
ikdysfm
 
Python dictionary : past, present, future
delimitry
 

What's hot (20)

PDF
Programmation fonctionnelle en JavaScript
Loïc Knuchel
 
PDF
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
Fabio Collini
 
KEY
Why Learn Python?
Christine Cheung
 
PDF
The Ring programming language version 1.5.2 book - Part 45 of 181
Mahmoud Samir Fayed
 
PDF
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
Fabio Collini
 
PDF
Using Scala Slick at FortyTwo
Eishay Smith
 
PPTX
Python GC
delimitry
 
PDF
CoffeeScript
Scott Leberknight
 
ODP
Intro
Cosmin Poieana
 
PDF
Observational Science With Python and a Webcam
Intellovations, LLC
 
PDF
The Ring programming language version 1.3 book - Part 83 of 88
Mahmoud Samir Fayed
 
PPTX
Benefits of Kotlin
Benjamin Waye
 
PDF
Groovy collection api
trygvea
 
PDF
Haskell in the Real World
osfameron
 
PDF
Pytables
rocketcircus
 
KEY
Code as data as code.
Mike Fogus
 
PDF
Rデバッグあれこれ
Takeshi Arabiki
 
PDF
The Ring programming language version 1.10 book - Part 56 of 212
Mahmoud Samir Fayed
 
PDF
python高级内存管理
rfyiamcool
 
PDF
Visualization of Supervised Learning with {arules} + {arulesViz}
Takashi J OZAKI
 
Programmation fonctionnelle en JavaScript
Loïc Knuchel
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
Fabio Collini
 
Why Learn Python?
Christine Cheung
 
The Ring programming language version 1.5.2 book - Part 45 of 181
Mahmoud Samir Fayed
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
Fabio Collini
 
Using Scala Slick at FortyTwo
Eishay Smith
 
Python GC
delimitry
 
CoffeeScript
Scott Leberknight
 
Observational Science With Python and a Webcam
Intellovations, LLC
 
The Ring programming language version 1.3 book - Part 83 of 88
Mahmoud Samir Fayed
 
Benefits of Kotlin
Benjamin Waye
 
Groovy collection api
trygvea
 
Haskell in the Real World
osfameron
 
Pytables
rocketcircus
 
Code as data as code.
Mike Fogus
 
Rデバッグあれこれ
Takeshi Arabiki
 
The Ring programming language version 1.10 book - Part 56 of 212
Mahmoud Samir Fayed
 
python高级内存管理
rfyiamcool
 
Visualization of Supervised Learning with {arules} + {arulesViz}
Takashi J OZAKI
 
Ad

Viewers also liked (20)

PPTX
Python 활용: 이미지 처리와 데이터 분석
용 최
 
PPTX
Python 표준 라이브러리
용 최
 
PPTX
Python 웹 프로그래밍
용 최
 
PPTX
Java와 Python의 만남: Jython과 Sikuli
용 최
 
PPTX
Python 생태계의 이해
용 최
 
PPTX
Python on Android
용 최
 
PPTX
Python 이해하기 20160815
Yong Joon Moon
 
PDF
Python quick guide1
Kanchilug
 
PPTX
141103 최창원 파이썬 확장 프로그래밍
Changwon Choe
 
PDF
Character Encoding in python
daesung7kang
 
PDF
병렬 프로그래밍
준혁 이
 
PDF
라즈베리파이 와 스카이로버 나노에 만남
Jae Sang Lee
 
PDF
20151219_(python_korea)_How_to_automate_webhacking.kr_with_Python_presentation
re4lfl0w
 
PPTX
Python의 계산성능 향상을 위해 Fortran, C, CUDA-C, OpenCL-C 코드들과 연동하기
Ki-Hwan Kim
 
PPTX
병렬 프로그래밍 패러다임
codenavy
 
PPTX
파이썬 함수 이해하기
Yong Joon Moon
 
PDF
병렬프로그래밍과 Cuda
Seok-joon Yun
 
PDF
PyCon 12월 세미나 - 실전 파이썬 프로그래밍 책 홍보
Young Hoo Kim
 
PDF
Python Recipes for django girls seoul
Joeun Park
 
PPTX
파이썬 병렬프로그래밍
Yong Joon Moon
 
Python 활용: 이미지 처리와 데이터 분석
용 최
 
Python 표준 라이브러리
용 최
 
Python 웹 프로그래밍
용 최
 
Java와 Python의 만남: Jython과 Sikuli
용 최
 
Python 생태계의 이해
용 최
 
Python on Android
용 최
 
Python 이해하기 20160815
Yong Joon Moon
 
Python quick guide1
Kanchilug
 
141103 최창원 파이썬 확장 프로그래밍
Changwon Choe
 
Character Encoding in python
daesung7kang
 
병렬 프로그래밍
준혁 이
 
라즈베리파이 와 스카이로버 나노에 만남
Jae Sang Lee
 
20151219_(python_korea)_How_to_automate_webhacking.kr_with_Python_presentation
re4lfl0w
 
Python의 계산성능 향상을 위해 Fortran, C, CUDA-C, OpenCL-C 코드들과 연동하기
Ki-Hwan Kim
 
병렬 프로그래밍 패러다임
codenavy
 
파이썬 함수 이해하기
Yong Joon Moon
 
병렬프로그래밍과 Cuda
Seok-joon Yun
 
PyCon 12월 세미나 - 실전 파이썬 프로그래밍 책 홍보
Young Hoo Kim
 
Python Recipes for django girls seoul
Joeun Park
 
파이썬 병렬프로그래밍
Yong Joon Moon
 
Ad

Similar to Python 내장 함수 (20)

PDF
Investigating Python Wats
Amy Hanlon
 
PDF
An overview of Python 2.7
decoupled
 
PDF
A tour of Python
Aleksandar Veselinovic
 
PDF
Python Usage (5-minute-summary)
Ohgyun Ahn
 
PDF
python.pdf
wekarep985
 
PPTX
Basics of Python programming (part 2)
Pedro Rodrigues
 
PDF
Quick python reference
Jayant Parida
 
PDF
Data types
Rajesh Kone
 
PDF
Advanced python
EU Edge
 
PPTX
Code Like Pythonista
Chiyoung Song
 
PDF
Beautiful python - PyLadies
Alicia Pérez
 
PDF
Python 2.5 reference card (2009)
gekiaruj
 
PPTX
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
PDF
Python-3-compiled-Cheat-Sheet-version-3.pdf
letsdism
 
ODP
Python basics
Himanshu Awasthi
 
PDF
Intro to Python
OSU Open Source Lab
 
PPTX
Python Training
TIB Academy
 
PDF
Welcome to python
Kyunghoon Kim
 
PPT
python language programming presentation
lbisht2
 
PPT
python within 50 page .ppt
sushil155005
 
Investigating Python Wats
Amy Hanlon
 
An overview of Python 2.7
decoupled
 
A tour of Python
Aleksandar Veselinovic
 
Python Usage (5-minute-summary)
Ohgyun Ahn
 
python.pdf
wekarep985
 
Basics of Python programming (part 2)
Pedro Rodrigues
 
Quick python reference
Jayant Parida
 
Data types
Rajesh Kone
 
Advanced python
EU Edge
 
Code Like Pythonista
Chiyoung Song
 
Beautiful python - PyLadies
Alicia Pérez
 
Python 2.5 reference card (2009)
gekiaruj
 
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
Python-3-compiled-Cheat-Sheet-version-3.pdf
letsdism
 
Python basics
Himanshu Awasthi
 
Intro to Python
OSU Open Source Lab
 
Python Training
TIB Academy
 
Welcome to python
Kyunghoon Kim
 
python language programming presentation
lbisht2
 
python within 50 page .ppt
sushil155005
 

Recently uploaded (20)

PDF
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
PPTX
Presentation about variables and constant.pptx
safalsingh810
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
Immersive experiences: what Pharo users do!
ESUG
 
PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PDF
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PDF
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
Presentation about variables and constant.pptx
safalsingh810
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
Immersive experiences: what Pharo users do!
ESUG
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 

Python 내장 함수

  • 1. 파이썬 내장 함수 정보기술 시대에 유익한 파이썬 프로그래밍 – 제 6 강 (2) 동양미래대학교 2015.7 최용 <[email protected]>
  • 3. Python3 내장 함수 Built-in Functi ons abs() dict() help() min() setattr() all() dir() hex() next() slice() any() divmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod() bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray() filter() issubclass() pow() super() bytes() float() iter() print() tuple() callable() format() len() property() type() chr() frozenset() list() range() vars() classmethod() getattr() locals() repr() zip() compile() globals() map() reversed() __import__() complex() hasattr() max() round() delattr() hash() memoryview() set() https://docs.python.org/3/library/functions.html
  • 4. abs() >>> abs(-3) 3 >>> abs(-3.0) 3.0 >>> z = complex(1, 2) >>> abs(z) 2.23606797749979
  • 5. all() >>> all([True, True, True]) True >>> all([True, False, True]) False
  • 6. any() >>> any([True, False, True]) True >>> any((False, False, False)) False
  • 8. bin() >>> bin(1) '0b1' >>> bin(2) '0b10' >>> bin(3) '0b11' >>> bin(4) '0b100'
  • 9. bool() >>> bool(True) True >>> bool(2 < 3) True >>> bool(1) True >>> bool(3 % 2) True >>> bool(not None) True >>> bool(False) False >>> bool(2 > 3) False >>> bool(0) False >>> bool(4 % 2) False >>> bool(None) False >>> bool() False
  • 10. bytearray() >>> data = bytearray(b'Monty Python') >>> data[5] = 33 # mutable >>> data bytearray(b'Monty!Python') http://python3porting.com/problems.html#manipulating-binary-data http://dabeaz.blogspot.kr/2010/01/few-useful-bytearray-tricks.html
  • 11. bytes() >>> b'Python' b'Python' >>> type(b'Python') <class 'bytes'> >>> b'파이썬' File "<stdin>", line 1 SyntaxError: bytes can only contain ASCII literal characters. >>> bytes('Python', 'utf-8') b'Python' >>> bytes('파이썬', 'utf-8') b'xedx8cx8cxecx9dxb4xecx8dxac'
  • 12. callable() >>> def sum(x, y): ... return x + y ... >>> callable(sum) True >>> x = 10 >>> callable(x) False >>> class MyClass: ... pass ... >>> callable(MyClass) True >>> obj = MyClass() >>> callable(obj) False http://joequery.me/code/python-builtin-functions/#callable
  • 14. classmethod() >>> class Pizza: ... radius = 42 ... @classmethod ... def get_radius(cls): ... return cls.radius ... >>> Pizza.get_radius() 42 https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods
  • 15. compile() >>> codeobj = compile('x = 2nprint("X is " + str(x))', # source ... 'fakemodule', # file name ... 'exec') # mode >>> exec(codeobj) X is 2 http://stackoverflow.com/questions/22443939/python-built-in-function-compile-what-is-it-used-for
  • 16. complex() >>> x = complex("4+2j") >>> x (4+2j) >>> y = complex("4-5j") >>> y (4-5j) >>> x+y (8-3j) >>> x*y (26-12j) >>> complex("4") (4+0j) http://joequery.me/code/python-builtin-functions/#complex
  • 17. delattr() >>> class Employee: ... def __init__(self, name, salary): ... self.name = name ... self.salary = salary ... >>> j = Employee("John", "2000$") >>> j.salary '2000$' >>> delattr(j, "salary") >>> hasattr(j, "salary") False
  • 18. dict() >>> dict() {} >>> dict( [[1, 'a'], [2, 'b'], [3, 'c']] ) {1: 'a', 2: 'b', 3: 'c'} >>> dict( ((1, 'a'), (2, 'b'), (3, 'c')) ) {1: 'a', 2: 'b', 3: 'c'}
  • 19. dir() >>> class Shape: ... def __dir__(self): ... return ['area', 'perimeter', 'location'] ... >>> s = Shape() >>> dir(s) ['area', 'location', 'perimeter'] >>> import struct >>> dir(struct) ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__pack age__', '__spec__', '_clearcache', 'calcsize', 'error', 'iter_unpack', 'pack', 'pack_into', 'unpack', 'unpack_ from']
  • 20. divmod() >>> divmod(7, 3) (2, 1) >>> divmod(8.4, 4.2) (2.0, 0.0) >>> divmod(8.5, 4.2) (2.0, 0.09999999999999964)
  • 21. enumerate() >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
  • 22. eval() >>> x = 1 >>> eval('x + 1') 2 >>> y = eval('x + 2') >>> y 3 >>> a = 10 >>> b = 5 >>> D = {'a': 2, 'b': 3} >>> eval('a + b') 15 >>> eval('a + b', D) 5
  • 23. exec() >>> a = 3 >>> exec('b = 2') # eval()과 달리, 값을 리턴하지 않음 >>> exec('c = a + b') >>> c 5
  • 24. filter() >>> N = range(1, 11) >>> Even = list() >>> for n in N: ... if n % 2 == 0: ... Even.append(n) ... >>> Even [2, 4, 6, 8, 10] >>> Odd = list(filter(lambda x: x % 2, N)) >>> Odd [1, 3, 5, 7, 9]
  • 25. float() >>> float(1) 1.0 >>> float(1.234) 1.234 >>> float('+1.23') 1.23 >>> float(' -12345n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf
  • 26. format() >>> L = [['a', 123], ['by', 45.6], ['cow', 7.89]] >>> for s, n in L: ... print(s, n) ... a 123 by 45.6 cow 7.89 >>> for s, n in L: ... print(format(s, '^10') + '|' + format(n, '<.2f')) ... a |123.00 by |45.60 cow |7.89 http://joequery.me/code/python-builtin-functions/#format
  • 27. frozenset() set • mutable • add() • remove() frozenset • immutable: 생성된 이후에는 내용을 변경할 수 없음
  • 28. getattr() >>> class MyClass: ... x = 0 ... y = 1 ... >>> myobj = MyClass() >>> getattr(myobj, 'x') 0
  • 29. globals() >>> globals() {'__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__loader__': <class '_frozen_ importlib.BuiltinImporter'>, '__spec__': None, '__ doc__': None, '__package__': None} >>> balance = 200 >>> cost = 50 >>> globals() {'__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'balance': 200, '__loader__': < class '_frozen_importlib.BuiltinImporter'>, '__spe c__': None, '__doc__': None, '__package__': Non e, 'cost': 50} >>> eval('balance - cost') 150 >>> mylocals = {'cost': 75} >>> eval('balance - cost', mylocals) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'balance' is not defined >>> eval('balance - cost', globals(), mylocals) 125 http://joequery.me/code/python-builtin-functions/#eval
  • 30. hasattr() >>> class MyClass: ... x = 0 ... y = 1 ... >>> myobj = MyClass() >>> hasattr(myobj, 'y') True >>> hasattr(myobj, 'z') False
  • 31. hash() >>> hash('One little, two little, three little indians') -7814896826006998464 >>> hash('indian') -8497506485016990678 >>> hash('boy') 2674027540618413217 >>> hash('One little, two little, three little indians') -7814896826006998464 >>> hash('indian') -8497506485016990678 http://stackoverflow.com/questions/7646520/is-this-an-appropriate-use-of-pythons-built-in-hash-function http://www.pythoncentral.io/hashing-strings-with-python/
  • 32. help() >>> help(eval) Help on built-in function eval in module builtins: eval(...) eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.
  • 33. hex() >>> for n in range(20): ... print(hex(n)) ... 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc 0xd 0xe 0xf 0x10 0x11 0x12 0x13
  • 34. id() >>> a = 1 >>> b = 2 >>> L = [a, b] >>> M = L >>> id(L[0]) 4297370688 >>> id(M[0]) 4297370688
  • 35. input() >>> s = input('Type any string: ') Type any string: Python >>> print(s) Python
  • 36. int() >>> n = int(input('Type any number: ')) Type any number: 3 >>> print(n * n) 9
  • 37. isinstance() >>> class Human: ... pass ... >>> me = Human() >>> isinstance(me, Human) True >>> class Robot: ... pass ... >>> you = Robot() >>> isinstance(you, Human) False >>> class Vehicle: ... pass ... >>> class Car(Vehicle): ... pass ... >>> mycar = Car() >>> isinstance(mycar, Car) True >>> isinstance(mycar, Vehicle) True
  • 38. issubclass() >>> class Vehicle: ... pass ... >>> class Car(Vehicle): ... pass ... >>> issubclass(Car, Vehicle) True
  • 39. iter() >>> my_list = [5, 1, 6, 3] >>> my_iter = iter(my_list) >>> next(my_iter) 5 >>> next(my_iter) 1 >>> next(my_iter) 6 >>> next(my_iter) 3
  • 41. list() >>> list([1, 2, 3]) [1, 2, 3] >>> list((1, 2, 3)) [1, 2, 3] >>> list('XYZxyz') ['X', 'Y', 'Z', 'x', 'y', 'z']
  • 42. locals() >>> def foo(arg): # 함수 foo는 로컬 네임스페이스에 두 개의 변수 arg와 x를 가짐 ... x = 1 ... print(locals()) ... >>> foo(7) # locals는 이름/값 사전을 리턴 {'x': 1, 'arg': 7} >>> foo('bar') {'x': 1, 'arg': 'bar'} http://www.diveintopython.net/html_processing/locals_and_globals.html
  • 43. map() for … in … >>> M = list() >>> for x in range(1, 6): ... M.append(x % 2) ... >>> M [1, 0, 1, 0, 1] map() >>> map(lambda x: x % 2, range(1, 6)) <map object at 0x101a67d30> >>> list(_) [1, 0, 1, 0, 1]
  • 44. max() >>> max(1234, 234, 34, 4) 1234 >>> max([3, 9, 27]) 27 >>> max('return') 'u'
  • 45. memoryview() >>> ba = bytearray(b'abcdefgh') >>> mv = memoryview(ba) >>> mv[4:6] <memory at 0x0000000002BB7CC8> >>> mv[4:6].tobytes() b'ef' >>> mv[4:6] = b'ZA' >>> ba bytearray(b'abcdZAgh') http://eli.thegreenplace.net/2011/11/28/less-copies-in-python-with-the-buffer-protocol-and-memoryviews
  • 46. min() >>> min(1234, 234, 34, 4) 4 >>> min('invest') 'e'
  • 47. next() >>> my_list = [5, 1, 6, 3] >>> my_iter = iter(my_list) >>> next(my_iter) 5 >>> next(my_iter) 1 >>> next(my_iter) 6 >>> next(my_iter) 3
  • 48. object() >>> obj = object() >>> type(obj) <class 'object'>
  • 49. oct() >>> for n in range(1, 21): ... print(str(n) + ': ' + oc t(n)) ... 1: 0o1 2: 0o2 3: 0o3 4: 0o4 5: 0o5 6: 0o6 7: 0o7 8: 0o10 9: 0o11 10: 0o12 11: 0o13 12: 0o14 13: 0o15 14: 0o16 15: 0o17 16: 0o20 17: 0o21 18: 0o22 19: 0o23 20: 0o24
  • 50. open() >>> with open("test.txt", "wt") as out_file: ... out_file.write("This Text is going to out filenLook at it and see!") ... 50 >>> with open("test.txt", "rt") as in_file: ... text = in_file.read() ... >>> print(text) This Text is going to out file Look at it and see! https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/File_IO
  • 53. print() >>> print('Python 3.4') Python 3.4 >>> print('Python', '3.4') Python 3.4 >>> print('Python', '3.4', sep=' ') Python 3.4 >>> print('Python', '3.4', sep=' _') Python_3.4 >>> for x in range(3): ... print(x, end='n') ... 0 1 2 >>> for x in range(3): ... print(x, end='t') ... 0 1 2 >>>
  • 54. property() class C: def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x >>> c = C() >>> c.x = 10 >>> print(c.x) 10 >>> del c.x >>> help(C) Help on class C in module __main__: class C(builtins.object) | Methods defined here: | | __init__(self) | | ----------------------------------------------------------- ----------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | x | I'm the 'x' property.
  • 55. range() >>> range(10) range(0, 10) >>> list(range(5)) [0, 1, 2, 3, 4] >>> tuple(range(5)) (0, 1, 2, 3, 4) >>> for x in range(0, 10, 2): ... print(x) ... 0 2 4 6 8 >>> for y in range(10, 0, -1): ... print(y) ... 10 9 8 7 6 5 4 3 2 1
  • 57. reversed() >>> reversed([0, 1, 2, 3, 4]) <list_reverseiterator object at 0x101a67c50> >>> list(reversed([0, 1, 2, 3, 4])) [4, 3, 2, 1, 0]
  • 59. set() >>> A = set([n for n in range(2, 31, 2)]) >>> 4 in A True >>> len(A) 15 >>> A.add(32) >>> A {32, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30} >>> {4, 8, 12}.issubset(A) True >>> {4, 8, 12} < A True >>> B = set([n for n in range(3, 31, 3)]) >>> C = A.intersection(B) >>> C {24, 18, 12, 6, 30} >>> A.issuperset(C) True >>> sorted(C) [6, 12, 18, 24, 30] >>> D = A.union(B) >>> D {2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 26, 27, 28, 30}
  • 60. setattr() >>> class Employee: ... def __init__(self, name, salary): ... self.name = name ... self.salary = salary ... >>> j = Employee("John", "2000$") >>> j.salary '2000$' >>> setattr(j, "salary", "3000$") >>> j.salary '3000$' >>> setattr(j, "gender", "male") >>> j.gender 'male'
  • 61. slice() >>> L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> L[2:7] [2, 3, 4, 5, 6] >>> L[2:7:2] [2, 4, 6] >>> s = slice(2, 7) >>> L[s] [2, 3, 4, 5, 6] >>> s = slice(2, 7, 2) >>> L[s] [2, 4, 6]
  • 62. sorted() >>> sorted([2, 3, 6, 4, 5, 20]) [2, 3, 4, 5, 6, 20]
  • 63. staticmethod() >>> class Util: ... @staticmethod ... def add(a, b): ... return a + b ... >>> Util.add(2, 3) 5 http://pyengine.blogspot.kr/2011/08/staticmethod-vs-classmethod.html
  • 64. str() >>> str(1) '1' >>> str('a') 'a' >>> str([1, 'a']) "[1, 'a']" >>> str(None) 'None'
  • 66. super() class LoggingDict(dict): def __setitem__(self, key, value): logging.info('Settingto %r' % (key, value)) super().__setitem__(key, value) https://rhettinger.wordpress.com/2011/05/26/super-considered-super/
  • 67. tuple() >>> tuple([1, 2, 3]) (1, 2, 3) >>> tuple((1, 2, 3)) (1, 2, 3) >>> tuple('XYZxyz') ('X', 'Y', 'Z', 'x', 'y', 'z')
  • 68. type() >>> type(2) <class 'int'> >>> type('boy') <class 'str'> >>> type([2, 'boy']) <class 'list'> >>> type(None) <class 'NoneType'> >>> import calendar >>> type(calendar) <class 'module'> >>> class MyClass: ... pass ... >>> mc = MyClass() >>> type(mc) <class '__main__.MyClass'>
  • 69. vars() >>> class Employee: ... def __init__(self, name, salary): ... self.name = name ... self._salary = salary ... ... >>> j = Employee("John", "2000$") >>> vars(j) {'name': 'John', '_salary': '2000$'}
  • 70. zip() >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> list(zipped) [(1, 4), (2, 5), (3, 6)] >>> list(zipped) []
  • 71. __import__() >>> from math import pi >>> pi 3.141592653589793 >>> _temp = __import__('math', globals(), locals(), ['pi'], 0) >>> pi = _temp.pi >>> pi 3.141592653589793

Editor's Notes

  • #30: Return the dictionary containing the current scope's global variables.
  • #31: hasattr(...) hasattr(object, name) -> bool Return whether the object has an attribute with the given name. (This is done by calling getattr(object, name) and catching AttributeError.)
  • #32: hash(...) hash(object) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely.
  • #35: id(...) id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.)
  • #43: locals(...) locals() -> dictionary Update and return a dictionary containing the current scope's local variables.
  • #46: class memoryview(object) | memoryview(object) | | Create a new memoryview object which references the given object.
  • #72: Note  This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().