Python/Python

[Python] builtin abs() 함수

상쾌한기분 2021. 1. 7. 18:04
반응형

abs(x) 함수는 입력 받은 값의 절대값을 return 해주는 함수이다.

정의

def abs(*args, **kwargs): # real signature unknown
    Return the absolute value of the argument.

실행결과

sample = [
    10, - 10,
    10.5, - 10.5,
    0, 0.0,
]
for s in sample:
    print('{} => {}'.format(s, abs(s)))

"""
10    => 10
-10   => 10
10.5  => 10.5
-10.5 => 10.5
0     => 0
0.0   => 0.0
"""

이런식으로도 사용이 가능하다.

from operator import __abs__

__abs__(10)

구현단

PyObject *
PyNumber_Absolute(PyObject *o)
{
    PyNumberMethods *m;

    if (o == NULL) {
        return null_error();
    }

    m = Py_TYPE(o)->tp_as_number;
    if (m && m->nb_absolute)
        return m->nb_absolute(o);

    return type_error("bad operand type for abs(): '%.200s'", o);
}
tp_as_number


PyNumberMethods* PyTypeObject.tp_as_number

Pointer to an additional structure that contains fields relevant only to objects which implement the number protocol. These fields are documented in Number Object Structures.

Inheritance:
The tp_as_number field is not inherited, but the contained fields are inherited individually.

nb_absolute

 

728x90
반응형