파이썬[Python]: 내장함수 - __bool__ 메서드

파이썬(Phthon): 내장함수 - __bool__ 메서드(method)


/// 설명

True 값을 테스트하고 내장함수 bool() 을 구현하기 위해 호출 됩니다.

참고: __len__()

※ 형식
object.__bool__(self)

reference
https://docs.python.org/3/reference/datamodel.html

/// 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class A:
    def __init__(self, a):
        self.a = a
 
    def __bool__(self):
        return bool(self.a)
 
 
print(A('').__bool__())  # False
print(A('string').__bool__())  # True
 
= A('')
print(bool(a))  # False
= A('string')
print(bool(a))  # True
 
 
# if no __bool__(), then __len__() will be used.(fall back)
class B:
    def __init__(self, a):
        self.a = a
 
    def __len__(self):
        return len(self.a)
 
 
= B('')
print(bool(a))  # False
= B('string')
print(bool(a))  # True
 
 
# if defines neither __bool__() nor __len__(), all are considered True.
class C:
    def __init__(self, a):
        self.a = a
 
 
= C(False)
print(bool(a))  # True
 
 
cs

* 실행환경: Microsoft Windows 10 Homes
* 인터프리터: 파이썬(Python 3.9)


– 당신을 응원합니다. –

댓글

이 블로그의 인기 게시물

파이썬[Python]: 내장함수 - from_bytes 메서드

파이썬[Python]: 내장함수 - __len__ 메서드

파이썬[Python]: kivy - 한글 사용

파이썬[Python]: 내장함수 - bit_length 메서드

C 언어: sin 함수, cos 함수, tan 함수