개체의 특성 나열
클래스의 인스턴스에 존재하는 특성 목록을 가져올 수 있는 방법이 있는가?
class new_class():
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
a = new_class(2)
print(', '.join(a.SOMETHING))
원하는 결과는 "multi, str"가 출력된다는 것이다.대본의 여러 부분에서 현재의 속성을 볼 수 있도록 하기 위해서입니다.
>>> class new_class():
... def __init__(self, number):
... self.multi = int(number) * 2
... self.str = str(number)
...
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])
당신은 또한 pprint가 도움이 될 수도 있다.
dir(instance)
# or (same value)
instance.__dir__()
# or
instance.__dict__
그런 다음 어떤 유형이 있는지 테스트할 수 있다.type()
또는 의 방법인 경우callable()
.
이전 답변은 모두 정답이며, 질문하는 내용에 대해 세 가지 옵션이 있음
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'multi', 'str']
>>> vars(a)
{'multi': 4, 'str': '2'}
>>> a.__dict__
{'multi': 4, 'str': '2'}
vars(obj)
객체의 속성을 반환한다.
모듈 검사:
검사 모듈은 모듈, 클래스, 방법, 기능, 트레이스백, 프레임 객체, 코드 오브젝트 등의 라이브 오브젝트에 대한 정보를 얻는 데 도움이 되는 몇 가지 유용한 기능을 제공한다.
사용.getmembers()
당신은 당신의 클래스의 모든 속성과 그 가치를 볼 수 있다.개인 또는 보호된 속성을 제외하려면 다음을 사용하십시오..startswith('_')
. 방법 또는 함수를 제외하려면 다음을 사용하십시오.inspect.ismethod()
또는inspect.isfunction()
.
import inspect
class NewClass(object):
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
def func_1(self):
pass
a = NewClass(2)
for i in inspect.getmembers(a):
# Ignores anything starting with underscore
# (that is, private and protected attributes)
if not i[0].startswith('_'):
# Ignores methods
if not inspect.ismethod(i[1]):
print(i)
:ismethod()
의 두 번째 요소에 사용됨i
첫째는 단순히 문자열이기 때문에(그 이름은)
오프토픽:클래스 이름은 CamelCase를 사용하십시오.
>>> ', '.join(i for i in dir(a) if not i.startswith('__'))
'multi, str'
물론 이것은 클래스 정의에 있는 어떤 방법이나 속성도 인쇄할 것이다.변경하여 "개인" 메서드를 제외할 수 있음i.startwith('__')
로i.startwith('_')
사용할 수 있다dir(your_object)
속성이를 getattr(your_object, your_object_attr)
가치를 얻다
사용법:
for att in dir(your_object):
print (att, getattr(your_object,att))
이것은 당신의 물체에 __dict_가 없는 경우에 특히 유용하다.그렇지 않은 경우 var(your_object)도 시도해 보십시오.
종종 당신이 사용해야 할 특성들의 전체 목록을 나열하기 위해 언급된다.dir()
그러나 일반인들의 믿음과는 반대로dir()
모든 속성을 끄집어내는 것은 아니다.예를 들어, 당신은 그것을 알아차릴 수 있다.__name__
반에서 빠져 있을 수도 있다.dir()
클래스 자체에서 액세스할 수 있지만 나열하십시오.다음 날짜의 문서에서dir()
(피톤 2, 파이톤 3):
dir()는 주로 대화형 프롬프트에서 사용하기 위한 편의성으로 제공되기 때문에, 엄격하게 또는 일관되게 정의된 이름의 집합을 제공하려고 하는 것보다 흥미로운 이름의 집합을 더 많이 제공하려고 하며, 자세한 행동은 릴리스에 따라 달라질 수 있다.예를 들어, 인수가 클래스인 경우 메타클라스 속성은 결과 목록에 없다.
리스트가 반환된 이후 완전성을 보장하지는 않지만, 다음과 같은 기능은 더 완전한 경향이 있다.dir()
이행을 포함한 많은 요인에 의해 영향을 받을 수 있다.__dir__()
메서드 또는 사용자 정의__getattr__()
또는__getattribute__()
반이나 학부모 중 한 명에게 말이야자세한 내용은 제공된 링크를 참조하십시오.
def dirmore(instance):
visible = dir(instance)
visible += [a for a in set(dir(type)).difference(visible)
if hasattr(instance, a)]
return sorted(visible)
이 작업을 수행하는 방법에는 두 가지가 있다.
#! /usr/bin/env python3
#
# This demonstrates how to pick the attiributes of an object
class C(object) :
def __init__ (self, name="q" ):
self.q = name
self.m = "y?"
c = C()
print ( dir(c) )
실행 시 이 코드는 다음을 생성한다.
jeffs@jeff-desktop:~/skyset$ python3 attributes.py
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'm', 'q']
jeffs@jeff-desktop:~/skyset$
왜 이걸 원해?정확한 의도를 모르는 상태에서 최선의 답을 얻기는 어려울지도 모른다.
클래스의 인스턴스를 특정 방식으로 표시하려면 이 작업을 수동으로 수행하는 것이 거의 항상 더 낫다.여기에는 당신이 원하는 것이 정확히 포함되고 원하지 않는 것은 포함하지 않을 것이며, 순서는 예측할 수 있을 것이다.
클래스의 내용을 표시하는 방법을 찾고 있는 경우, 관심 있는 속성을 수동으로 포맷하고 이 속성을 다음 형식으로 제공하십시오.
__str__
또는__repr__
네 반을 위한 방법이야객체가 어떻게 작동하는지 이해할 수 있도록 어떤 방법과 그러한 방법이 존재하는지 알아보려면
help
.help(a)
해당 문서에 기반한 오브젝트 클래스에 대한 형식화된 출력을 보여준다.dir
어떤 물체의 모든 속성을 프로그래밍적으로 얻기 위해 존재한다.(액세스 중)__dict__
같은 집단이지만 나 자신을 이용하지는 않을 무언가를 한다.)그러나, 이것은 당신이 원하는 것을 포함하지 않을 수도 있고 당신이 원하지 않는 것을 포함할 수도 있다.그것은 믿을 수 없고 사람들은 그들이 그들보다 훨씬 더 자주 그것을 원한다고 생각한다.다소 직교적인 노트에, 현재 Python 3에 대한 지원은 거의 없다.만약 당신이 진짜 소프트웨어를 쓰는데 관심이 있다면 당신은 numpy, lxml, Twisted, PL 또는 아직 Python 3을 지원하지 않고 너무 빨리 계획이 없는 많은 웹 프레임워크와 같은 제3자 자료를 원할 것이다.2.6 지점과 3.x 지점의 차이는 작지만 도서관 지원의 차이는 크다.
순서대로 실행된 python 셸 스크립트를 참조하십시오. 여기서 쉼표로 구분된 문자열 형식의 클래스의 속성을 볼 수 있다.
>>> class new_class():
... def __init__(self, number):
... self.multi = int(number)*2
... self.str = str(number)
...
>>> a = new_class(4)
>>> ",".join(a.__dict__.keys())
'str,multi'<br/>
나는 python 3.4를 사용하고 있다.
이 대답들 외에도, 나는 사실상 어떤 가치의 전체 구조를 분출하는 함수(피톤 3)를 포함시킬 것이다.그것은 사용한다.dir
속성 이름의 전체 목록을 설정한 다음getattr
모든 값의 모든 멤버의 유형을 표시하며, 가능한 경우 전체 멤버를 표시한다.
import json
def get_info(obj):
type_name = type(obj).__name__
print('Value is of type {}!'.format(type_name))
prop_names = dir(obj)
for prop_name in prop_names:
prop_val = getattr(obj, prop_name)
prop_val_type_name = type(prop_val).__name__
print('{} has property "{}" of type "{}"'.format(type_name, prop_name, prop_val_type_name))
try:
val_as_str = json.dumps([ prop_val ], indent=2)[1:-1]
print(' Here\'s the {} value: {}'.format(prop_name, val_as_str))
except:
pass
이제 다음 중 어느 하나라도 통찰력을 주어야 한다.
get_info(None)
get_info('hello')
import numpy
get_info(numpy)
# ... etc.
개체의 특성 가져오기
class new_class():
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
new_object = new_class(2)
print(dir(new_object)) #total list attributes of new_object
attr_value = new_object.__dict__
print(attr_value) #Dictionary of attribute and value for new_class
for attr in attr_value: #attributes on new_class
print(attr)
출력
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__','__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'multi', 'str']
{'multi': 4, 'str': '2'}
multi
str
사용 전 작성한 바와 같이obj.__dict__
일반적인 사례를 처리할 수 있지만 일부 클래스는__dict__
속성 및 사용(메모리 효율성에 대한 요구 사항).
보다 탄력적인 방법의 예:
class A(object):
__slots__ = ('x', 'y', )
def __init__(self, x, y):
self.x = x
self.y = y
class B(object):
def __init__(self, x, y):
self.x = x
self.y = y
def get_object_attrs(obj):
try:
return obj.__dict__
except AttributeError:
return {attr: getattr(obj, attr) for attr in obj.__slots__}
a = A(1,2)
b = B(1,2)
assert not hasattr(a, '__dict__')
print(get_object_attrs(a))
print(get_object_attrs(b))
이 코드의 출력:
{'x': 1, 'y': 2}
{'x': 1, 'y': 2}
참고1:
파이톤은 역동적인 언어인데, 이 코드조차도 몇몇 경우를 놓칠 수 있기 때문에 당신이 그 속성들을 얻으려고 하는 클래스를 항상 더 잘 아는 것이다.
참고2:
이 코드는 클래스 변수가 제공되지 않음을 의미하는 인스턴스 변수만 출력한다.예를 들면 다음과 같다.
class A(object):
url = 'http://stackoverflow.com'
def __init__(self, path):
self.path = path
print(A('/questions').__dict__)
코드 출력:
{'path': '/questions'}
이 코드는 다음 항목을 인쇄하지 않음url
클래스 속성 및 원하는 클래스 속성을 생략할 수 있음.
때때로 우리는 속성이 인스턴스 멤버라고 생각할 수 있지만, 이 예제를 사용하여 표시되지 않거나 표시되지 않을 것이다.
- 사용.
__dict__
또는vars
빗나가서 효과가 없다.__slots__
. - 사용.
__dict__
그리고__slots__
빗나가서 효과가 없다.__slots__
기초 계급 출신 - 사용.
dir
메서드나 속성과 같은 클래스 속성과 객체 속성이 포함되기 때문에 작동하지 않는다. - 사용.
vars
사용하는 것과 같다.__dict__
.
이게 내가 가진 최선이다:
from typing import Dict
def get_attrs( x : object ) -> Dict[str, object]:
mro = type( x ).mro()
attrs = { }
has_dict = False
sentinel = object()
for klass in mro:
for slot in getattr( klass, "__slots__", () ):
v = getattr( x, slot, sentinel )
if v is sentinel:
continue
if slot == "__dict__":
assert not has_dict, "Multiple __dicts__?"
attrs.update( v )
has_dict = True
else:
attrs[slot] = v
if not has_dict:
attrs.update( getattr( x, "__dict__", { } ) )
return attrs
다음 Python 셸 스크립팅 실행을 순서대로 참조하십시오. 그러면 클래스 생성부터 인스턴스의 필드 이름 추출까지 솔루션이 제공된다.
>>> class Details:
... def __init__(self,name,age):
... self.name=name
... self.age =age
... def show_details(self):
... if self.name:
... print "Name : ",self.name
... else:
... print "Name : ","_"
... if self.age:
... if self.age>0:
... print "Age : ",self.age
... else:
... print "Age can't be -ve"
... else:
... print "Age : ","_"
...
>>> my_details = Details("Rishikesh",24)
>>>
>>> print my_details
<__main__.Details instance at 0x10e2e77e8>
>>>
>>> print my_details.name
Rishikesh
>>> print my_details.age
24
>>>
>>> my_details.show_details()
Name : Rishikesh
Age : 24
>>>
>>> person1 = Details("",34)
>>> person1.name
''
>>> person1.age
34
>>> person1.show_details
<bound method Details.show_details of <__main__.Details instance at 0x10e2e7758>>
>>>
>>> person1.show_details()
Name : _
Age : 34
>>>
>>> person2 = Details("Rob Pike",0)
>>> person2.name
'Rob Pike'
>>>
>>> person2.age
0
>>>
>>> person2.show_details()
Name : Rob Pike
Age : _
>>>
>>> person3 = Details("Rob Pike",-45)
>>>
>>> person3.name
'Rob Pike'
>>>
>>> person3.age
-45
>>>
>>> person3.show_details()
Name : Rob Pike
Age can't be -ve
>>>
>>> person3.__dict__
{'age': -45, 'name': 'Rob Pike'}
>>>
>>> person3.__dict__.keys()
['age', 'name']
>>>
>>> person3.__dict__.values()
[-45, 'Rob Pike']
>>>
attributes_list = [attribute for attribute in dir(obj) if attribute[0].islower()]
__attrs__
인스턴스의 속성 목록을 제공한다.
>>> import requests
>>> r=requests.get('http://www.google.com')
>>> r.__attrs__
['_content', 'status_code', 'headers', 'url', 'history', 'encoding', 'reason', 'cookies', 'elapsed', 'request']
>>> r.url
'http://www.google.com/'
>>>
참조URL: https://stackoverflow.com/questions/2675028/list-attributes-of-an-object
'IT이야기' 카테고리의 다른 글
대응 라우터를 사용하여 사이드바 유지 (0) | 2022.03.17 |
---|---|
Vuetify 양식 검증 재설정 (0) | 2022.03.17 |
React Native 프로젝트에서 어떤 폴더를 선택하십시오. (0) | 2022.03.17 |
POST 요청을 보내는 방법? (0) | 2022.03.17 |
VueRouter는 URL을 변경하지만 구성 요소는 변경하지 않음 (0) | 2022.03.17 |