Как вывести список методов и атрибутов объекта x
Перейти к содержимому

Как вывести список методов и атрибутов объекта x

  • автор:

Как получить полный список методов и атрибутов объекта?

не возвращает шаблон как один из элементов списка. А именно, он возвращает:

Согласно руководству, предполагается, что он содержит

имена атрибутов объекта, имена его атрибутов класса и рекурсивно атрибутов его класса.

В нем также говорится, что

Список не обязательно завершен.

Есть ли способ получить список полный? Я всегда предполагал, что dir возвращает полный список, но, по-видимому, он не.

Также: есть ли способ перечислять только атрибуты? Или только методы?

Изменить: это на самом деле ошибка в python → предположительно, она исправлена ​​в ветке 3.0 (и, возможно, также в версии 2.6)

4 ответа

Для полного списка атрибутов короткий ответ: no. Проблема в том, что атрибуты фактически определяются как аргументы, принятые встроенной функцией getattr . Так как пользователь может переопределить __getattr__ , внезапно разрешая любой атрибут, нет возможности генерировать этот список. Функция dir возвращает ключи в атрибуте __dict__ , т.е. Все доступные атрибуты, если метод __getattr__ не переопределяется.

Во втором вопросе это не имеет смысла. На самом деле, методы являются атрибутами, подлежащими вызову, и ничего больше. Вы можете фильтровать вызываемые атрибуты и, используя модуль inspect , определить методы, методы или функции класса.

Типы данных, основные конструкции. Python.

Первая пачка ответов на вопросы из какого-то собеседования, линк к сожалению потерялся. В принципе вопросы довольно простые, если знать немножко про функциональное программирование и ориентироваться в стандартных функциях.

1. Как получить список всех атрибутов объекта?

Очень просто, используя стандартную функцию dir. В качестве аргумента передаем тот самый объект, в данном случае (для примера) объект string.

Модуль inspect предоставляет несколько очень полезных методов которые позволяют собирать информацию о объектах Python, это достаточно важно, т.к. питон динамический ЯП и в нем очень просто сделать вещи которые обычно называют «хакерскими». Используя inspect можно получить содержимое класса, получить исходный код метода (ага, и поменять его), выделить формат и список аргументов функции и т.д.

2. Как получить список всех публичных атрибутов объекта?

Private методы в Python начинаются с «__» поэтому все что нужно сделать чтобы получить список public аттрибутов это отфильтровать все, что начинается с «__». Тут будет уместно использовать элемент функционального программирования — функцию filter(f, lst) которая формирует новый список элементов последовательности — lst руководствуясь функцией f.

3. Как получить список методов объекта?

Используя функцию callable() которая как бы говорит реально ли вызвать объект или нет. если вызвать реально — то это метод, если нет — то свойство

How to Print Object Attributes in Python? (with Code)

How to Print Object Attributes in Python? (with Code)

Python is an object-oriented programming language. In fact, everything in Python is an object (even a class)! Every object has some attributes associated with them. Now, to work well with any object you must know about its attributes.

Hence in this article, we’ll discuss objects, attributes, and ways to print these objects’ attributes in Python. So, let’s get started.

What is an Object in Python?

An object is an instance of a class. It is often regarded as a real-world entity. An object may constitute properties, data (or), and a few methods to operate on that data. It is needed to instantiate a class. Each object has a unique identity.

For instance, consider the human race as a class. So each human will have a name, age, weight, height, and many other properties. Each person can be uniquely identified as an object, (including me, you, your friend, or any other human you know!)

Let’s take an example of how to declare an object in Python:

Note that the name and age variables are attributes of the objects of class ‘human’.

Output:

The above example displays how an object is created (for a user-defined class) and accessed in Python. We have also declared attributes of the object (here, human1 & human2) and accessed them.

declare object attributes

Now, we should take a better look at the attributes of an object.

What is an Attribute in Python?

An attribute can be defined as a property of a class or an object. These are data members inside a class (or object) that represents their features. These attributes can be properties (state or value) defining an object or any method acting upon that object.

For instance, let’s take our previous example: class human. The name and age variables declared in the class human are actually ‘attributes’ of ‘human’. Along with them, actions (functions) like running, sleeping, reading, walking, and swimming are also attributes of ‘human’.

You might get confused between an attribute and an object. The difference between an object and an attribute is that An object is a real-world entity while an attribute is a characteristic of that object.

person and object

These attributes are generally defined within a class and shared among all the instances (objects) of that class. An object can be accessed using these attributes.

Attributes are also classified into two types:

  1. Class Attributes
  2. Instance (object) Attributes

An Instance attribute is a data member of an object. It is associated with the properties of an object. So, every instance of that class will have the same instance attributes. (It is the purpose of a class, after all!). Their scope of access also lies within the object creation.

For instance, refer to the variables ‘name’ and ‘age’ of class ‘human’. These are instance variables, allocated to every object separately.

Class Attributes is a data member of the whole class. These attributes share the same memory space and are accessed by all the objects in common.

To learn more about attributes, check our article on static variables in python.

Now that we have learned about objects and attributes, we’re all set to learn how to print all attributes of an object in Python.

4 Ways to Print all Attributes of an Object in Python

In order to code efficiently and access an object to obtain its full functionality, one must be aware of all the attributes of the object. Thus, given below are different ways to print all attributes of an object in Python.

01) Using __dir__() method

Python offers an in-built method to print out all attributes of an object (Now, this object may be anything in Python). This method is also known as a magic method or a dunder method in Python.

Syntax:

print(objectName.__dir__())

Let’s jump on to an example for better understanding:

Output:

Note that the method returns a list with the user-defined attributes given priority.

You’ll be surprised to know that, the __dir__() method can also be modified. You can define the __dir__() method in a class to override the default __dir__() method. Let’s modify the __dir__() method for the above example:

Output:

The s.__dir__() statement calls for the user-defined method which overrides the default dunder method. Notice how different the outputs of the default __dir__() method and the user-defined __dir__() method are.

02) Using dir()

Python offers an in-built function to list out all the attributes of an object. This function returns all attributes (variables, methods, or objects) associated with the passed parameter, in a given scope.

Syntax:

print(dir(parameter))

Passing the parameter is optional. If you don’t pass a parameter, the dir() function will return all the attributes in the local scope.

Let’s take an example:

Output:

See! The dir() function returned all the in-built and user-defined attributes in the local scope.

Although the above example had a small list, sometimes the output is long enough to have low readability. To deal with this, Python offers a pprint module.

The «pprint module» is used to print the list in a well-formatted way. Take a look at the example below.

Example: To print the attributes of objects in Python by using the dir() function with an object as an argument.

Output:

The pprint() method relates directly to «pretty print»! Take note of how each feature is printed on a separate line. This improves the output’s readability.
Now that we’ve seen some dir() examples, let’s go over some key points about the dir() function:

  1. It returns a list of all the characteristics of an object in the local scope.
  2. It internally invokes the __dir__() function. Internally, the dir() function implements its functionality via the __dir__() method.
  3. The dir() function provides an alphabetically sorted output.

Before moving to the next method, let’s compare the dir() and __dir__() methods.

Working with dir() function and __dir__() method

a. You already know that the dir() function internally calls for __dir__() method for implementation. Hence, defining the __dir__() method will also change the functionality (and hence output) of the dir() function. Let’s take the above example and call the dir() method:

Output:

Notice the difference between the outputs returned by dir() function and the __dir__() method. While the __dir__() method provides the defined list as-it-is, the dir() function produces a sorted list of attributes.

b. Now let’s take another example of modifying the __dir__() method. You’ll be surprised by the output:

Output:

The __dir__() method works fine but the dir() function produces a TypeError. You must be wondering WHY!

The code did work for the previous example, didn’t it? So why the error? Because the dir() method compares the attributes to produce a sorted list as output. Hence, since the types, string («alice») and integer (1,2 and rest), cannot be compared with each other, therefore calling dir() method on this produces an error.

Note: The dir() function, in absence of the __dir__() method, calls for the __dict__ attribute to return a list of all the attributes of an object in Python.

03) Using vars() function

Python offers the vars() function which returns a ‘dictionary’ of all the instance attributes along with their values. It is similar to the above methods, the only difference being, vars() focuses only on instance attributes and also returns their values along with them.

print(vars(objectName))

Passing any parameter to the vars() function is optional. It can also be called without passing any parameter to it.

Let’s take a few examples to understand the different cases:

a. Without passing any parameter

Output:

Note how each attribute is followed by its value.

b. Passing parameter to the vars() function

Output:

When the object (here s) is passed as an argument to the vars() method, it produces a dictionary of only the attributes associated with the instance, leaving out the rest of the attributes (as obtained in the above example).

Also, note that the vars() function internally calls for the __dict__ attribute for implementation. The __dict__ attribute is simply a dictionary containing all attributes of that object.

Let’s look at the output when we use the __dict__ attribute in the above example:

Output:

The output is same! (Hence, remember that the vars() function will produce an error when passed over an object which does not have the __dir__ attribute.)

04) Using inspect module

The inspect module in Python helps in inspecting certain modules or objects that are included in the code. It includes several useful functions that provide information about live objects (like class, function, object, and methods). It can be used to obtain an analysis of objects, for example, to examine a class’s content or to display information about an object.

To print all the attributes of an object in Python, you can use the ‘getmembers()‘ function of the inspect module. This function returns the list of tuples containing the attributes along with their values.

Refer to the below image for better readability of the output:

attribute value

Let’s take an example for a better understanding:

I’ve used pprint module to increase the readability of the output.

Output:

Note that this list contains tuples in sorted order. So, the getmembers() function returns a sorted list of all the attributes of an object in Python, along with their respective values.

Conclusion

So far we’ve discussed different ways to print all attributes of an object in Python. But before moving on to list out all the attributes, you must be able to differentiate between instance attributes and class attributes. So, try and test out these methods along with their variations to understand them better.

How to get a complete list of object's methods and attributes? [duplicate]

does not return pattern as one of the lists’s elements. Namely it returns:

According to the manual, it is supposed to contain

the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

It says also that

The list is not necessarily complete.

Is there a way to get the complete list? I always assumed that dir returns a complete list but apparently it does not.

Also: is there a way to list only attributes? Or only methods?

Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)

5 Answers 5

For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr built-in function. As the user can reimplement __getattr__ , suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir function returns the keys in the __dict__ attribute, i.e. all the attributes accessible if the __getattr__ method is not reimplemented.

For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect module determine the class methods, methods or functions.

That is why the new __dir__() method has been added in python 2.6

    (scroll down a little bit)

Here is a practical addition to the answers of PierreBdR and Moe:

    For Python >= 2.6 and new-style classes, dir() seems to be enough.

For old-style classes, we can at least do what a standard module does to support tab completion: in addition to dir() , look for __class__ , and then to go for its __bases__ :

(Test code and output are deleted for brevity, but basically for new-style objects we seem to have the same results for get_object_attrs() as for dir() , and for old-style classes the main addition to the dir() output seem to be the __class__ attribute.)

wjandrea's user avatar

ジョージ's user avatar

Only to supplement:

    dir() is the most powerful/fundamental tool. (Most recommended)

Solutions other than dir() merely provide their way of dealing the output of dir() .

Listing 2nd level attributes or not, it is important to do the sifting by yourself, because sometimes you may want to sift out internal vars with leading underscores __ , but sometimes you may well need the __doc__ doc-string.

IMPORTANT: __dir__() can be sometimes overwritten with a function, value or type, by the author for whatever purpose.

Here is an example:

TypeError: descriptor __dir__ of ‘object’ object needs an argument

The author of PyTorch modified the __dir__() method to something that requires an argument. This modification makes dir() fail.

If you want a reliable scheme to traverse all attributes of an object, do remember that every pythonic standard can be overridden and may not hold, and every convention may be unreliable.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *