Як отримати список атрибутів класу в Python?
Клас — це визначений користувачем план або прототип, з якого створюються об’єкти. Класи забезпечують засоби групування даних і функціональних можливостей. Створення нового класу створює новий тип об’єкта, що дозволяє створювати нові екземпляри цього типу. Кожен екземпляр класу може мати атрибути, прикріплені до нього для підтримки його стану. Екземпляри класу також можуть мати методи (визначені його класом) для зміни свого стану.
приклад:
Python3
# 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().
Щоб отримати список усіх атрибутів, методів разом із деякими успадкованими магічними методами класу, ми використовуємо вбудований під назвою ви() .
приклад:
Python3
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__', '__Settttt__', ' ', '__str__', '__subclasshook__', '__weakref__', 'attr', 'one', 'show', 'three', '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() який повертає список атрибутів і методів класу.
приклад:
Python3
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__ . Цей метод повертає лише атрибути екземпляра.
приклад:
Python3
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(). Цей метод повертає словник атрибутів екземпляра даного об’єкта.
Python3
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}