파이썬[Python]: 내장함수 - type 함수
내장함수 - type 함수(function)
/// 설명
객체의 타입을 반환하며, object.__class__ 와 같은 값을 가집니다.
인자 3 개를 사용할 경우에는 새로운 객체를 생성합니다.
참고: isinstance()
※ 형식
class type(object)
class type(name, bases, dict, **kwds)
reference
https://docs.python.org/3/library/functions.html
인자 3 개를 사용할 경우에는 새로운 객체를 생성합니다.
참고: isinstance()
※ 형식
class type(object)
class type(name, bases, dict, **kwds)
reference
https://docs.python.org/3/library/functions.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 43 44 45 46 47 48 | import types def func_a(): pass class A: pass test_1 = 1 test_2 = 'string' test_3 = [1, 2, 3, 4, 5] test_4 = lambda: 1 print(type(test_1)) # <class 'int'> print(type(test_2)) # <class 'str'> print(type(test_3)) # <class 'list'> print(type(test_4)) # <class 'function'> print(type(func_a)) # <class 'function'> print(type(A())) # <class '__main__.A'> print(test_1.__class__) # <class 'int'> print(test_2.__class__) # <class 'str'> print(test_3.__class__) # <class 'list'> print(test_4.__class__) # <class 'function'> print(func_a.__class__) # <class 'function'> print(A().__class__) # <class '__main__.A'> print(isinstance(test_1, int)) # True print(isinstance(test_2, str)) # True print(isinstance(test_3, list)) # True print(isinstance(test_4, types.FunctionType)) # True print(isinstance(func_a, types.FunctionType)) # True print(isinstance(A(), object)) # True # My and Ny are same class My: a = 1 my = My() print(my) # <__main__.My object at 0x000001328F411F40> Ny = type('Ny', (), dict(a=1)) ny = Ny() print(ny) # <__main__.Ny object at 0x000001328F411F10> | cs |
/// 예제 객체 생성(method 포함)
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 | class A(object): def __init__(self, a): self.a = a def func(self): return self.a print(A.__dict__) # {'__module__': '__main__', '__init__': <function A.__init__ at 0x000002A4FAA640D0>, 'func': <function A.func at 0x000002A4FAA64160>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None} a = A(1) print(a) # <__main__.A object at 0x000002A4FAA6DFD0> print(a.func()) # 1 # I'm not sure but I tried(class A and below are same) test = dict({'__init__': A.__dict__['__init__'], 'func': A.__dict__['func']}) B = type('B', (object,), test) print(B.__dict__) # {'__init__': <function A.__init__ at 0x000002A4FAA640D0>, 'func': <function A.func at 0x000002A4FAA64160>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'B' objects>, '__weakref__': <attribute '__weakref__' of 'B' objects>, '__doc__': None} b = B(1) print(b) # <__main__.B object at 0x000002A4FAA6DF70> print(b.func()) # 1 | cs |
* 실행환경: Microsoft Windows 10 Homes
* 인터프리터: 파이썬(Python 3.9)
– 당신을 응원합니다. –
댓글
댓글 쓰기