1.命令介绍
最近学习并使用了一个python的内置函数dir,首先help一下:
>>> help(dir)
Help on built-in function dir in module __builtin__:
dir()
dir([object]) -> list of strings
Return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it:
No argument: the names in the current scope.
Module object: the module attributes.
Type or class object: its attributes, and recursively the attributes of
its bases.
Otherwise: its attributes, its class's attributes, and recursively the
attributes of its class's base classes.
通过help,可以简单的认为dir列出指定对象或类的属性。
2.实例
下面是一个简单的测试:
class A:
def a(self):
pass
class A1(A):
def a1(self):
pass
if __name__ == '__main__':
print("dir without arguments:", dir())
print("dir class A:", dir(A))
print("dir class A1:", dir(A1))
a = A1()
print("dir object a(A1):", dir(a))
print("dir function a.a:", dir(a.a))
测试结果:
dir without arguments: ['A', 'A1', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
dir class A: ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a']
dir class A1: ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'a1']
dir object a(A1): ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'a1']
dir function a.a: ['__call__', '__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
3.使用dir查找module下的所有类
最初使用这个函数的初衷,就是在一个module中查找实现的类名,通过该函数可以很容易的实现。
比如把上面的测试程序保存为A.py,再建一个测试程序,内容如下:
import A
if __name__ == '__main__':
print("dir module A:", dir(A))
结果如下:
dir module A: ['A', 'A1', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
可以看出class A和A1都能够找到。
4.如何找到当前模块下的类
这是一个烦恼较长时间的一个问题,也没有搜到详细的解决方法,下面是我的集中实现方法。
4.1.方法一:在module下面直接调用
比如在上面的A.py最下面添加一行,即可在后续的代码中可以使用selfDir来查找当前的module下的类,修改后的代码如下:
class A:
def a(self):
pass
class A1(A):
def a1(self):
pass
curModuleDir=dir() # get dir of current file(module)
if __name__ == '__main__':
print("dir without arguments:", dir())
print("dir class A:", dir(A))
print("dir class A1:", dir(A1))
a = A1()
print("dir object a(A1):", dir(a))
print("dir function a.a:", dir(a.a))
print("dir current file:", curModuleDir)
4.2.方法二:import当前module
把当前module和别的import一样引用,代码如下:
# A.py
import A as this # import current module
class A:
def a(self):
pass
class A1(A):
def a1(self):
pass
if __name__ == '__main__':
print("dir without arguments:", dir())
print("dir class A:", dir(A))
print("dir class A1:", dir(A1))
a = A1()
print("dir object a(A1):", dir(a))
print("dir function a.a:", dir(a.a))
print("dir current file:", dir(this))
4.3.方法三:根据module名称查找module,然后调用dir
我们知道module下面有个属性__name__显示module名称,怎么能够根据module名称来查找module对象呢?可以借助sys.modules。代码如下:
import sys
class A:
def a(self):
pass
class A1(A):
def a1(self):
pass
if __name__ == '__main__':
print("dir without arguments:", dir())
print("dir class A:", dir(A))
print("dir class A1:", dir(A1))
a = A1()
print("dir object a(A1):", dir(a))
print("dir function a.a:", dir(a.a))
print("dir current file:", dir(sys.modules[__name__])) # 使用__name__获取当前module对象,然后使用对象获得dir

Python은 게임 및 GUI 개발에서 탁월합니다. 1) 게임 개발은 Pygame을 사용하여 드로잉, 오디오 및 기타 기능을 제공하며 2D 게임을 만드는 데 적합합니다. 2) GUI 개발은 Tkinter 또는 PYQT를 선택할 수 있습니다. Tkinter는 간단하고 사용하기 쉽고 PYQT는 풍부한 기능을 가지고 있으며 전문 개발에 적합합니다.

Python은 데이터 과학, 웹 개발 및 자동화 작업에 적합한 반면 C는 시스템 프로그래밍, 게임 개발 및 임베디드 시스템에 적합합니다. Python은 단순성과 강력한 생태계로 유명하며 C는 고성능 및 기본 제어 기능으로 유명합니다.

2 시간 이내에 Python의 기본 프로그래밍 개념과 기술을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우기, 2. 마스터 제어 흐름 (조건부 명세서 및 루프), 3. 기능의 정의 및 사용을 이해하십시오. 4. 간단한 예제 및 코드 스 니펫을 통해 Python 프로그래밍을 신속하게 시작하십시오.

Python은 웹 개발, 데이터 과학, 기계 학습, 자동화 및 스크립팅 분야에서 널리 사용됩니다. 1) 웹 개발에서 Django 및 Flask 프레임 워크는 개발 프로세스를 단순화합니다. 2) 데이터 과학 및 기계 학습 분야에서 Numpy, Pandas, Scikit-Learn 및 Tensorflow 라이브러리는 강력한 지원을 제공합니다. 3) 자동화 및 스크립팅 측면에서 Python은 자동화 된 테스트 및 시스템 관리와 같은 작업에 적합합니다.

2 시간 이내에 파이썬의 기본 사항을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우십시오. 이를 통해 간단한 파이썬 프로그램 작성을 시작하는 데 도움이됩니다.

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Python 3.6에 피클 파일로드 3.6 환경 보고서 오류 : modulenotfounderror : nomodulename ...


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

WebStorm Mac 버전
유용한 JavaScript 개발 도구

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