Python에 메서드가 있는지 확인하는 방법은 무엇입니까?
함수에서__getattr__()참조된 변수를 찾을 수 없으면 오류가 발생합니다.변수 또는 메서드가 개체의 일부로 존재하는지 확인하려면 어떻게 해야 합니까?
import string
import logging
class Dynamo:
def __init__(self,x):
print "In Init def"
self.x=x
def __repr__(self):
print self.x
def __str__(self):
print self.x
def __int__(self):
print "In Init def"
def __getattr__(self, key):
print "In getattr"
if key == 'color':
return 'PapayaWhip'
else:
raise AttributeError
dyn = Dynamo('1')
print dyn.color
dyn.color = 'LemonChiffon'
print dyn.color
dyn.__int__()
dyn.mymethod() //How to check whether this exist or not
수업에 그런 방법이 있는지 확인하세요?
hasattr(Dynamo, key) and callable(getattr(Dynamo, key))
또는
hasattr(Dynamo, 'mymethod') and callable(getattr(Dynamo, 'mymethod'))
사용할 수 있습니다.self.__class__대신에Dynamo
용서를 구하는 것이 허락을 구하는 것보다 쉽습니다.
메서드가 있는지 확인하지 않습니다.코드 한 줄을 "확인"에 낭비하지 마십시오.
try:
dyn.mymethod() # How to check whether this exists or not
# Method exists and was used.
except AttributeError:
# Method does not exist; What now?
어때.dir()앞에서 기능하는.getattr()?
>>> "mymethod" in dir(dyn)
True
저는 아래의 유틸리티 기능을 사용합니다.람다, 클래스 메소드 및 인스턴스 메소드에서 작동합니다.
유틸리티 방법
def has_method(o, name):
return callable(getattr(o, name, None))
사용 예
테스트 클래스를 정의합니다.
class MyTest:
b = 'hello'
f = lambda x: x
@classmethod
def fs():
pass
def fi(self):
pass
이제 시도할 수 있습니다.
>>> a = MyTest()
>>> has_method(a, 'b')
False
>>> has_method(a, 'f')
True
>>> has_method(a, 'fs')
True
>>> has_method(a, 'fi')
True
>>> has_method(a, 'not_exist')
False
'inspect' 모듈을 사용해 볼 수 있습니다.
import inspect
def is_method(obj, name):
return hasattr(obj, name) and inspect.ismethod(getattr(obj, name))
is_method(dyn, 'mymethod')
에서 찾아보는 건 어때요?dyn.__dict__?
try:
method = dyn.__dict__['mymethod']
except KeyError:
print "mymethod not in dyn"
모든 방법이 호출 가능하다고 가정하면 이렇게 될 수도 있습니다.
app = App(root) # some object call app
att = dir(app) #get attr of the object att #['doc', 'init', 'module', 'button', 'hi_there', 'say_hi']
for i in att:
if callable(getattr(app, i)):
print 'callable:', i
else:
print 'not callable:', i
메서드가 클래스 외부에 있는데 이 메서드를 실행하지 않고 메서드가 없으면 예외를 발생시키려면 다음을 수행합니다.
'mymethod' in globals()
단순함을 좋아하는 사람들을 위해.
class ClassName:
def function_name(self):
return
class_name = ClassName()
print(dir(class_name))
# ['__init__', .... ,'function_name']
answer = 'function_name' in dir(class_name)
print("is'function_name' in class ? >> {answer}")
# is 'function_name' in class ? >> True
제 생각에 당신은 그것을 봐야 할 것 같습니다.inspect꾸러미그것은 당신이 어떤 것들을 '포장'할 수 있게 해줍니다.를 사용할 때dir메소드는 또한 메소드, 상속된 메소드 및 충돌을 가능하게 하는 다른 모든 속성을 나열합니다. 예:
class One(object):
def f_one(self):
return 'class one'
class Two(One):
def f_two(self):
return 'class two'
if __name__ == '__main__':
print dir(Two)
사용자가 얻을 수 있는 어레이dir(Two)두 가지를 모두 포함f_one그리고.f_two그리고 많은 내장된 것들.와 함께inspect다음을 수행할 수 있습니다.
class One(object):
def f_one(self):
return 'class one'
class Two(One):
def f_two(self):
return 'class two'
if __name__ == '__main__':
import inspect
def testForFunc(func_name):
## Only list attributes that are methods
for name, _ in inspect.getmembers(Two, inspect.ismethod):
if name == func_name:
return True
return False
print testForFunc('f_two')
이 예에서는 여전히 두 클래스의 두 가지 방법을 모두 나열하고 있지만 특정 클래스에서만 작동하도록 검사를 제한하려면 작업이 조금 더 필요하지만 가능합니다.
언급URL : https://stackoverflow.com/questions/7580532/how-to-check-whether-a-method-exists-in-python
'codememo' 카테고리의 다른 글
| 전체 응용 프로그램을 세로 모드로만 설정하는 방법은 무엇입니까? (0) | 2023.08.21 |
|---|---|
| Ionic + Angular POST 요청 반환 상태 404 (0) | 2023.08.21 |
| jquery $는 실제로 무엇을 반환합니까? (0) | 2023.08.21 |
| PHPUunit: 여러 인수를 사용하여 여러 메서드 호출을 모의하려면 어떻게 해야 합니까? (0) | 2023.08.16 |
| Yii 2를 사용하여 Ajax 호출에서 잘못된 요청(#400)을 받는 중 (0) | 2023.08.16 |