Python에서 클래스 속성 목록을 얻는 방법은 무엇입니까?

클래스는 객체가 생성되는 사용자 정의 청사진 또는 프로토타입입니다. 클래스는 데이터와 기능을 함께 묶는 수단을 제공합니다. 새 클래스를 생성하면 새로운 유형의 객체가 생성되어 해당 유형의 새 인스턴스를 만들 수 있습니다. 각 클래스 인스턴스에는 상태를 유지하기 위해 속성이 첨부될 수 있습니다. 클래스 인스턴스에는 해당 상태를 수정하기 위한 메서드(클래스에 의해 정의됨)가 있을 수도 있습니다.

예:

파이썬3




# Python program to demonstrate> # classes> class> Student:> > > # class variable> > stream> => 'COE'> > > # Constructor> > def> __init__(> self> , name, roll_no):> > > self> .name> => name> > self> .roll_no> => roll_no> > # Driver's code> a> => Student(> 'Shivam'> ,> 3425> )> b> => Student(> 'Sachin'> ,> 3624> )> print> (a.stream)> print> (b.stream)> print> (a.name)> print> (b.name)> # Class variables can be accessed> # using class name also> print> (Student.stream)>

출력 :

COE COE Shivam Sachin COE 

메모: 자세한 내용은 다음을 참조하세요. Python 클래스 및 객체 .

클래스 속성 목록 가져오기

우리가 작업하는 속성을 아는 것이 중요합니다. 작은 데이터의 경우 속성의 이름을 기억하기 쉽지만 대용량 데이터의 경우 모든 속성을 기억하기가 어렵습니다. 운 좋게도 이 작업에 사용할 수 있는 Python의 일부 기능이 있습니다.

내장 dir() 함수 사용

클래스의 일부 상속된 매직 메서드와 함께 모든 속성, 메서드의 목록을 얻으려면 다음과 같은 내장 메서드를 사용합니다. 너() .

예:

파이썬3




class> Number :> > > # Class Attributes> > one> => 'first'> > two> => 'second'> > three> => 'third'> > > def> __init__(> self> , attr):> > self> .attr> => attr> > > def> show(> self> ):> > print> (> self> .one,> self> .two,> > self> .three,> self> .attr)> > n> => Number(> 2> )> n.show()> # Passing both the object> # and class as argument> # to the dir method> print> (> ' By passing object of class'> )> print> (> dir> (n))> print> (> ' By passing class itself '> )> print> (> dir> (Number))>

출력 :

첫 번째 두 번째 세 번째 2 클래스 ['__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__', 'attr', 'one', 'show', '3', 'two'] 클래스 자체를 전달하여 ['__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__', 'one', 'show' , '셋', '둘']

getmembers() 메소드 사용

속성 목록을 찾는 또 다른 방법은 모듈을 사용하는 것입니다. 검사하다 . 이 모듈은 다음과 같은 메소드를 제공합니다. getmembers() 클래스 속성 및 메소드 목록을 반환합니다.

예:

파이썬3




import> inspect> class> Number :> > > # Class Attributes> > one> => 'first'> > two> => 'second'> > three> => 'third'> > > def> __init__(> self> , attr):> > self> .attr> => attr> > > def> show(> self> ):> > print> (> self> .one,> self> .two,> > self> .three,> self> .attr)> > > # Driver's code> n> => Number(> 2> )> n.show()> # getmembers() returns all the> # members of an object> for> i> in> inspect.getmembers(n):> > > # to remove private and protected> > # functions> > if> not> i[> 0> ].startswith(> '_'> ):> > > # To remove other methods that> > # doesnot start with a underscore> > if> not> inspect.ismethod(i[> 1> ]):> > print> (i)>

출력 :

first second third 2 ('attr', 2) ('one', 'first') ('three', 'third') ('two', 'second') 

__dict__() 매직 메서드 사용

속성을 찾기 위해 매직 메소드를 사용할 수도 있습니다. __dict__ . 이 메서드는 인스턴스 속성만 반환합니다.

예:

파이썬3




class> Number :> > > # Class Attributes> > one> => 'first'> > two> => 'second'> > three> => 'third'> > > def> __init__(> self> , attr):> > self> .attr> => attr> > > def> show(> self> ):> > print> (> self> .one,> self> .two,> > self> .three,> self> .attr)> > # Driver's code> n> => Number(> 2> )> n.show()> # using __dict__ to access attributes> # of the object n along with their values> print> (n.__dict__)> # to only access attributes> print> (n.__dict__.keys())> # to only access values> print> (n.__dict__.values())>

산출:

first second third 2 {'attr': 2} dict_keys(['attr']) dict_values([2]) 

vars() 함수 사용

속성을 찾기 위해 vars() 함수를 사용할 수도 있습니다. 이 메소드는 주어진 객체의 인스턴스 속성 사전을 반환합니다.

파이썬3




import> inspect> class> Number :> > > # Class Attributes> > one> => 'first'> > two> => 'second'> > three> => 'third'> > > def> __init__(> self> , attr):> > self> .attr> => attr> > > def> show(> self> ):> > print> (> self> .one,> self> .two,> > self> .three,> self> .attr)> > # Driver's code> n> => Number(> 2> )> n.show()> # using the vars function> print> (> vars> (n))>

산출:

first second third 2 {'attr': 2}