산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

예제가 있는 Python의 type() 및 isinstance()

파이썬에서 type()이란 무엇입니까?

파이썬에는 입력으로 주어진 변수의 클래스 유형을 찾는 데 도움이 되는 type()이라는 내장 함수가 있습니다. 예를 들어 입력이 문자열이면 출력은 , 목록의 경우 등입니다.

type() 명령을 사용하면 단일 인수를 전달할 수 있으며 반환 값은 주어진 인수의 클래스 유형이 됩니다(예:type(object)).

type()에 세 개의 인수, 즉 type(name, bases, dict)를 전달할 수도 있습니다. 이 경우 새 유형 개체를 반환합니다.

이 자습서에서는 다음을 배우게 됩니다.

유형() 구문:

type()은 아래와 같이 두 가지 방법으로 사용할 수 있습니다.

 type(object)
type(namr, bases, dict)


매개변수 :유형(객체)

매개변수 :유형(이름, 기본, 사전)

반환 가치:

객체가 type()에 전달된 유일한 매개변수인 경우 객체의 유형을 반환합니다.

type에 전달된 매개변수가 type(object, bases, dict)인 경우에는 새로운 유형의 객체를 반환합니다.

유형()의 예

이 예제에는 문자열 값, 숫자, 부동 소수점 값, 복소수, 목록, 튜플, dict 및 집합이 있습니다. 각 변수에 대한 출력을 보기 위해 유형이 있는 변수를 사용합니다.

str_list = "Welcome to Guru99"
age = 50
pi = 3.14
c_num = 3j+10
my_list = ["A", "B", "C", "D"]
my_tuple = ("A", "B", "C", "D")
my_dict = {"A":"a", "B":"b", "C":"c", "D":"d"}
my_set = {'A', 'B', 'C', 'D'}

print("The type is : ",type(str_list))
print("The type is : ",type(age))
print("The type is : ",type(pi))
print("The type is : ",type(c_num))
print("The type is : ",type(my_list))
print("The type is : ",type(my_tuple))
print("The type is : ",type(my_dict))
print("The type is : ",type(my_set))

출력:

The type is :<class 'str'>
The type is :<class 'int'>
The type is :<class 'float'>
The type is :<class 'complex'>
The type is :<class 'list'>
The type is :<class 'tuple'>
The type is :<class 'dict'>
The type is :<class 'set'>

예:클래스 객체에 type() 사용

type()을 사용하여 클래스에서 생성된 객체를 확인하면 클래스 이름과 함께 클래스 유형을 반환합니다. 이 예제에서는 클래스를 생성하고 클래스 테스트에서 생성된 객체 유형을 확인합니다.

class test:
    s = 'testing'

t = test()
print(type(t))

출력:

<class '__main__.test'>

예:type()에서 name, bases, dict 사용

type(name, bases, dict) 구문을 사용하여 유형을 호출할 수도 있습니다.

type()에 전달된 세 개의 매개변수, 즉 name, bases 및 dict는 클래스 정의를 구성하는 구성요소입니다. name은 클래스 이름, bases는 기본 클래스, dict는 기본 클래스 속성의 사전입니다.

이 예에서는 type()의 name, bases, dict의 세 가지 매개변수를 모두 사용할 것입니다.

예:

class MyClass:
  x = 'Hello World'
  y = 50

t1 = type('NewClass', (MyClass,), dict(x='Hello World', y=50))
print(type(t1))
print(vars(t1))

출력:

<class 'type'>
{'x': 'Hello World', 'y': 50, '__module__': '__main__', '__doc__': None}

세 가지 인수를 모두 type() 에 전달하면 기본 클래스 속성으로 새 클래스를 초기화하는 데 도움이 됩니다.

파이썬에서 isinstance()란 무엇인가요?

Python isinstance는 Python 내장 함수의 일부입니다. Python isinstance()는 두 개의 인수를 취하고 첫 번째 인수가 두 번째 인수로 제공된 classinfo의 인스턴스이면 true를 반환합니다.

구문 isinstance()

isinstance(object, classtype)

매개변수

반환 값:

객체가 classtype의 인스턴스이면 true를 반환하고 그렇지 않으면 false를 반환합니다.

isinstance()의 예

이 섹션에서는 isinstance()를 배우기 위한 다양한 예제를 공부할 것입니다.

예시 :isinstance() 정수 검사

아래 코드는 정수 값 51을 int 유형과 비교합니다. 51의 유형이 int와 일치하면 true를 반환하고 그렇지 않으면 false를 반환합니다.

age = isinstance(51,int)
print("age is an integer:", age)

출력:

age is an integer: True

예시 :isinstance() 플로트 체크

이 예에서는 float 값을 float 유형과 비교할 것입니다. 즉, 3.14 값은 float 유형과 비교됩니다.

pi = isinstance(3.14,float)
print("pi is a float:", pi)

출력:

pi is a float: True

예:isinstance() 문자열 검사

message = isinstance("Hello World",str)
print("message is a string:", message)

출력:

message is a string: True

예시 :isinstance() 튜플 체크

코드는 튜플 유형의 튜플(1,2,3,4,5)을 확인합니다. 주어진 입력이 튜플 유형이면 true를 리턴하고 그렇지 않으면 false를 리턴합니다.

my_tuple = isinstance((1,2,3,4,5),tuple)
print("my_tuple is a tuple:", my_tuple)

출력:

my_tuple is a tuple: True

예시 :isinstance() 설정 체크

코드는 집합(유형이 설정된 {1,2,3,4,5})을 확인합니다. 주어진 입력이 유형 집합이면 true를 반환하고 그렇지 않으면 false를 반환합니다.

my_set = isinstance({1,2,3,4,5},set)
print("my_set is a set:", my_set)

출력:

my_set is a set: True

예:isinstance() 목록 확인

코드는 유형이 목록인 목록 [1,2,3,4,5]를 확인합니다. 주어진 입력이 목록 유형이면 true를 리턴하고 그렇지 않으면 false를 리턴합니다.

my_list = isinstance([1,2,3,4,5],list)
print("my_list is a list:", my_list)

출력:

my_list is a list: True

예:isinstance() 사전 확인

코드는 dict({"A":"a", "B":"b", "C":"c", "D":"d"}, dict 유형을 확인합니다. 다음과 같은 경우 true를 반환합니다. 주어진 입력은 dict 유형이고 그렇지 않은 경우 false입니다.

my_dict = isinstance({"A":"a", "B":"b", "C":"c", "D":"d"},dict)
print("my_dict is a dict:", my_dict)

출력:

my_dict is a dict: True

예:클래스에 대한 isinstance() 테스트

코드는 isinstance() 를 사용하여 클래스의 유형 검사를 보여줍니다. 클래스의 객체는 isinstance() 내부의 클래스 이름과 비교됩니다. 객체가 클래스에 속하면 true를 반환하고 그렇지 않으면 false를 반환합니다.

class MyClass:
    _message = "Hello World"

_class = MyClass()

print("_class is a instance of MyClass() : ", isinstance(_class,MyClass))

출력:

_class is a instance of MyClass() True

파이썬에서 type()과 isinstance()의 차이점

유형() isinstance()
Python에는 입력으로 주어진 변수의 클래스 유형을 찾는 데 도움이 되는 type()이라는 내장 함수가 있습니다. 파이썬에는 값을 주어진 유형과 비교하는 isinstance()라는 내장 함수가 있습니다. 주어진 값과 유형이 일치하면 true를 반환하고 그렇지 않으면 false를 반환합니다.
반환 값은 유형 개체입니다. 반환 값은 부울(참 또는 거짓)입니다.
class A:
my_listA = [1,2,3]

class B(A):
my_listB = [1,2,3]

print(type(A()) == A)
print(type(B()) == A)

출력:

True
False

유형의 경우 하위 클래스 검사는 false를 반환합니다.

class A:
my_listA = [1,2,3]

class B(A):
my_listB = [1,2,3]

print(isinstance(A(), A))
print(isinstance(B(), A))

출력:

True
True

isinstance()는 하위 클래스로 확인할 때 진실한 값을 제공합니다.

요약:


python

  1. C# 식, 문 및 블록(예제 포함)
  2. Python 유형 변환 및 유형 캐스팅
  3. 파이썬 숫자, 유형 변환 및 수학
  4. Raspberry Pi 및 Python으로 로봇 구축
  5. 예제가 있는 Python 문자열 count()
  6. Python String format() 예제로 설명
  7. 예제가 있는 Python 문자열 find() 메서드
  8. 예제가 있는 Python Lambda 함수
  9. 예제가 있는 Python round() 함수
  10. 예제가 있는 Python map() 함수