Python에서 이름으로 클래스의 하위 클래스 찾기
문제:
모든 클래스를 어떻게 검색할 수 있습니까? 해당 클래스를 사용하여 Python의 특정 기본 클래스에서 상속됩니다. 이름?
해결책:
Python은 이름으로 지정된 클래스의 하위 클래스를 찾는 우아한 접근 방식을 제공합니다. __subclasses__ 메소드를 통해 클래스의 하위 클래스를 직접 검색할 수 있습니다.
코드 설명:
Bar, Baz, 하위 클래스가 있는 Foo라는 기본 클래스가 있다고 가정합니다. Bing에서 다음 코드 조각은 다음의 사용법을 보여줍니다. __subclasses__:
class Foo(object): pass class Bar(Foo): pass class Baz(Foo): pass class Bing(Bar): pass # Get the subclasses of Foo foo_subclasses = Foo.__subclasses__() print("Subclass names:", [cls.__name__ for cls in foo_subclasses]) print("Subclasses themselves:", Foo.__subclasses__()) # Validate that the subclasses inherit from Foo for cls in Foo.__subclasses__(): print("Base class of {}: {}".format(cls, cls.__base__))
출력:
Subclass names: ['Bar', 'Baz'] Subclasses themselves: [<class>, <class>] Base class of <class>: <class> Base class of <class>: <class></class></class></class></class></class></class>
하위 하위 클래스 찾기:
하위 하위 클래스를 찾아야 하는 경우 재귀를 사용할 수 있습니다. function:
def all_subclasses(cls): return set(cls.__subclasses__()).union( [s for c in cls.__subclasses__() for s in all_subclasses(c)])
참고:
__subclasses__가 효과적으로 작동하려면 하위 클래스의 클래스 정의가 이전에 실행되어야 한다는 점에 유의하는 것이 중요합니다. 클래스 이름을 나타내는 문자열이 있는 경우 먼저 globals(), locals() 또는 importlib와 같은 기술을 사용하여 클래스를 검색할 수 있습니다.
위 내용은 Python에서 이름으로 클래스의 하위 클래스를 검색하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.