Python dot notation ( methods )

Asked

Viewed 441 times

3

How to create point notation methods, those that are called object.show () instead of show ( objec ), or they apply only to strings, if yes why exactly ?

  • 1

    You have knowledge about the object orientation paradigm?

  • 1

    see if it helps you https://answall.com/q/199737/101

  • 1

    Yeah Anderson, and after posting I thought the guys would actually think of a normal object call - of course thinking that all language is ' objects, but I asked with another purpose.

  • And what was that other purpose? I don’t think it was very clear.

2 answers

5


Python dot notation is used to retrieve object attributes. In particular in Python, there is no distinction at the moment when you use the point between an "attribute" and a "method" - as in Python everything is an object and what distinguishes the methods is that they are "calleble" ("callable") members of an object.

So to create a method, the most common way is to create a class, and define the methods within the class body with the notation def <nome> (self, [parametro, ...]): - exactly as we do with loose functions. After that, when creating instances of this class, the methods will be available:

class A:
    def b(self):
         print(f"Método b chamado no objeto {self}")

a = A()
a.b()

If you paste iso into intertive mode (Python 3.6) the output will be something like:

Método b chamado no objeto <__main__.A object at 0x7f19d24b77b8>

(For Python versions between 3.0 and 3.5, remove the "f-string" and use the ". format method").

There are other ways to put attributes recoverable by a point - for example the simple assignment - that can be done both in the class and in some instance of object. Continuing the example above:

def bla():
   print("bla chamado")

a.bla = bla

a.bla()

This time the "a" function becomes an instance attribute a of the class object A we create. The biggest difference being that this way it does not receive a reference to the instance itself automatically (see, the function bla was defined without the parameter self and it would be wrong if I were delcarada with self and used that way).

The rules that Python uses for instance or class taxes - and when it automatically adds the attribute self or not - are well defined in the language. - but require a certain study to be understood in its entirety, why cover all corner cases. For everyday use they are usually intuitive enough. The Data Model may be the best document to understand the language as a whole and these rules.

A simplified summary just to understand the most basic attribute search - after the point there is an attribute name, and the Python Runtime looks for the attribute in the object following these steps:

  • The method __getattribute__ the object is called with the parameters self and the attribute name. As a rule, classes defined in "day-to-day" code do not reset the method __getattribute__ - then this method is at the base of the Python object hierarchy - and proceeds to search for the attribute. The next steps actually occur within that __getattribute__ default. The first of the cases below that der "match" is returned as the attribute:
  • Python searches the class and superclass of the object if the attribute exists and is an object of type "data-Descriptor" (an object that in turn has the method __get__ And one of __set__ or __del__) - I won’t go into detail what happens if he finds to keep this response at an intermediate level. I only say that when we use the developer @property he falls in this case.
  • If you can’t find a descriptor, Python looks at the attribute __dict__ of the instance itself if there is a key with that name. S
  • Python searches the object class for an attribute with that name.
  • If not found in the class, it looks in the superclasses, following the order that is in the attribute .__mro__ class.
  • If not found yet, Python calls the method __getattr__ (is different from __getattribute__) class, baking the attribute name.
  • If the call to __getattr__ fail, an exception happens AttributeError and the attribute is not recovered.

It is also worth adding that for objects whose classes are defined directly in C, using the Python API, and not in pure Python, it is generally not possible to add new attributes or methods dynamically. That is, you cannot hang new methods in the classes str or int Python, as possible in Ruby.

  • Splendid reply, thank you very much.

3

Let’s start with an example where 4 methods are created, being a init, the first two with the notation show(obj) and the last with the call that you call 'point notation''.

See the code presented in this answer, running repl.it.

class collection1::
    def __init__(self):
        self.lst = [1,2,3,4,5]

    # Tamanho da collection (função len) 
    def __len__(self):    
        return len(self.lst)

    # Fornece a posição de um item na collection
    def __getitem__(self, position):
        return self.lst[position]

    # Apresenta a collection 
    def show(self):
        print (self.lst)   

Now let’s instantiate and execute the methods:

c = collection1()
print (len(c))
5

print (c[3])
4

c.show()
[1, 2, 3, 4, 5]

Methods with names started and ended with __ (dunderscore)
Are the special methods, called by some "magical methods", the main thing you should know about these methods is that Voce should not call them directly (although this can be done). Instead of using obj.__len__() or obj.__getitem__[3] one should use len(obj) and obj[3]. Note that if obj is a built-in type (built-in), such as list, str, etc. The interpreter will call a function (which may be in cpython) via a shortcut. If the class of which obj is an instance, has been implemented by Voce, the interpreter will call the instance method that Voce has implemented, in this case __getitem__ and/or __len__.

Because Len is not a method?
Luciano Ramalho in his book Python Fluent, claims that he asked this question to one of the "core Velopers" in 2013 and the key to the answer was a quote from The Zen of Python 'praticality Beats purity' (Practicality surpasses purity). I recommend the book (no, I’m not getting anything. : -) ) for more details.

By implementing our own str in our class:
Let’s assume that we needed or wanted to implement a str "put the beast" in our class, we would just have to implement __str__, thus:

def __str__(self):
    return 'Classe especial com uma lista simples'

Now we could use the function str as if it were a function embedded in python, the difference is that the interpreter will call our function:

obj = collection1()
print (obj)
Classe especial com uma lista simples

Completion
Except for the implementations of escpecial methods, most of the methods you develop, will be the type Voce calls "point notation", in fact, even the special methods have the same implementation (that of such notation) the difference is only in the call and the magic.

DEMO

  • Very good, thanks for the reply and indication of the book

  • 2

    It is worth putting that the magical methods are always started and ended with __ - why the effect of a method name only started with __ is completely different (here comes the name-mangling mechanism)

  • 1

    True, I started with dunderscores but, in reality it is: inicidados and deceased. I will edit. Thanks.

  • 1

    And unofficially are called by Dunder methods, for example: __len__ is the Dunder Len, as well as __x__ would be the Dunder x. Just a curiosity worth commenting on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.