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

Python에서 익명 클래스 및 개체 탐색

Python의 내장 type() 함수는 객체가 속한 클래스를 반환합니다. Python에서는 내장 클래스나 사용자 정의 클래스 모두 클래스 유형의 객체입니다.

class myclass:
 def __init__(self):
 self.myvar=10
 return
 
obj = myclass()
print ('class of int', type(int))
print ('class of list', type(list))
print ('class of dict', type(dict))
print ('class of myclass', type(myclass))
print ('class of obj', type(obj))

다음과 같은 출력이 생성됩니다 -

class of int <class 'type'>
class of list <class 'type'>
class of dict <class 'type'>
class of myclass <class 'type'>

type()에는 다음과 같이 세 개의 인수 버전이 있습니다. −

구문

newclass=type(name, bases, dict)

위 구문을 사용하면 클래스를 동적으로 생성할 수 있습니다. 함수 유형의 세 가지 인수는 −

입니다.

익명 수업 만들기

위 버전의 type() 함수를 사용하여 익명 클래스를 만들 수 있습니다. name 인수는 널 문자열이고, 두 번째 인수는 한 클래스인 객체 클래스의 튜플입니다(Python의 각 클래스는 객체 클래스에서 상속됩니다). 특정 인스턴스 변수를 세 번째 인수 사전으로 추가합니다. 지금은 비워두겠습니다.

anon=type('', (object, ), {})

익명 개체 생성

이 익명 클래스의 객체를 생성하려면 -

obj = anon()
print ("type of obj:", type(obj))

결과는 객체가 익명 클래스임을 보여줍니다

type of obj: <class '__main__.'>

익명 클래스 및 객체 예시

인스턴스 변수와 인스턴스 메소드를 동적으로 추가할 수도 있습니다. 이 예를 살펴보세요 -

def getA(self):
 return self.a
obj = type('',(object,),{'a':5,'b':6,'c':7,'getA':getA,'getB':lambda self : self.b})()
print (obj.getA(), obj.getB())

다음과 같은 출력이 생성됩니다 -

5 6

python

  1. Python time.sleep():코드에 지연 추가(예제)
  2. 파이썬 while 루프
  3. 파이썬 모듈
  4. 예제가 있는 Python Timeit()
  5. PyUnit 튜토리얼:Python 단위 테스트 프레임워크(예제 포함)
  6. Python XML Parser Tutorial:xml 파일 읽기 예제(Minidom, ElementTree)
  7. Python RegEx:re.match(), re.search(), re.findall() 예제 포함
  8. Python은 목록에서 중복을 제거합니다.
  9. 파이썬 시간 모듈
  10. Python 줄 바꿈:Python에서 줄 바꿈 없이 인쇄하는 방법