Meaning of these nomenclatures in Python and other languages, if the names are universal

Asked

Viewed 394 times

2

I would like to know the meaning with examples, if necessary, of the following names:

  • Class
  • Object
  • Attribute
  • Method

2 answers

3


The meanings of these terms are universal in computer science. Eventually some language may have other meanings for some of them, but it is still "allowed" to use them within the original form.

The example will be only in Python.

I like to give examples like the below, with a "hello world" of a 2D game, because it has examples of objects that can be "seen" on the screen in a very concrete way. In practice, most objects do not match something that is visible directly on the screen. (I speak of other examples at the end)

Class

There are several ways to write the definition of what a class is. I like to think of classes as a object aggregating methods and data (the attributes) which function as an independent assembly within its system modeling.

So, for example, in a spaceship shooter, a class to dipo "Naveinimiga" can contain the attributes of "speed", "direction", "posicao_na_tela". And the methods of "moving", "shooting" that are called as "actions" in the execution of the program.

Object

An "entity" in your system that aggregates all the data you need to auto-define, and the operations that can be done with this data. In languages that have explicit class statements (the Python case), in general each object is an "instance" of a class: that is, it aggregates the same methods and attributes as other objects in the same class, but the attributes are independent of each other.

In the example of the game of ships, a ship can be on the screen at the position (0,0) and have the color red. Another ship can be on the screen at position (200.0) and have the color blue. The two will share the same methods, and the types of attributes - but the data of each - the attributes are separated.

Attribute

It is a value associated with an object. If Voce knows how to program, it knows variables - the attributes are "variables attached to specific objects". When talking about objects, I mentioned some attributes that "ships" may have.

Method

If you already program, you know the concept of function: a limited code block, which will work with data passed to it, may or may not cause an effect outside of these attributes (print something in the terminal, save a data in a file, draw something on the screen), and return a value.

A method is a block of code very much like a function, but it is declared in a class, and when it is called it is linked to a specific object (a class instance). In Python are also declared in the same way functions and methods. The biggest conceptual difference is that a method can work with the attributes without needing all the data you will use to be passed as parameters.

For example, the "ship" class may have a "move" method, which, based on the "speed" attributes of the object itself, updates the "position" attributes'.

Python-specific

Python differs from some other languages because the attributes of objects in a class are not declared in the class in general - but rather dynamically created when a new object is created. When this happens, the language automatically calls the method with the special name __init__. In all methods, Python automatically includes a first parameter, which by convention we call "self": this parameter is a reference to the object itself. From there, using "." as a separator, we can associate attributes to our object.

Below, follows the example of a "ship" class that could be used in a little game. Then it follows the same class, with comments before each line describing everything.To be less abstract, I include a minimally functional program (you only need to install pygame together with Python):

import pygame

largura = 800
altura = 600
jogo_terminou = None


class Nave:
    def __init__(self, posicao, velocidade, cor):
        self.posicao = list(posicao)
        self.velocidade = velocidade
        self.cor = cor

    def movimentar(self):
        global jogo_terminou
        self.posicao[0] += self.velocidade[0]
        self.posicao[1] += self.velocidade[1]
        if self.posicao[0] > largura or self.posicao[1] > altura:
             jogo_terminou = True

    def desenha(self, tela):
         pygame.draw.rect(tela, self.cor, (self.posicao[0], self.posicao[1], 50, 50))


def principal():
    global jogo_terminou

    tela = pygame.display.set_mode((largura, altura))
    jogo_terminou = False

    nave1 = Nave(posicao=(0, 0), velocidade=(10, 5), cor=(255,0,0))
    nave2 = Nave(posicao=(largura, 0), velocidade=(-10, 10), cor=(0,0,255))

    while not jogo_terminou:
        nave1.movimentar()
        nave2.movimentar()

        tela.fill((0,0,0))

        nave1.desenha(tela)
        nave2.desenha(tela)

        pygame.display.flip()
        pygame.time.delay(100)

    pygame.quit()


principal()

Now, the same code with comments on what is being done on each line, including explaining what is specific to Pygame:

# importa o módulo pygame, que disponibiliza funcionalidade
# para criar uma janela e desenhar na mesma
import pygame


# algumas variáveis globais que usamos no programa.
largura = 800
altura = 600
jogo_terminou = None


# Abaixo, declaração da classe Nave

class Nave:

    # Método inicializador: é chamado quando o Python
    # cria uma "instância", ou seja "um objeto" da classe
    # Nave. Os parâmetros passados parar criar o objeto
    # são repassados para o método __init__ - junto com
    # o "self" que é inserido automaticamente.

    def __init__(self, posicao, velocidade, cor):
        # Para cada parâmetro passado,
        # cria o _atributo_ correspondente
        # neste objeto:
        self.posicao = list(posicao)   # o atributo é convertido para "lista" para
                                       # que os componentes x e y possam ser atualizados
                                       # separadamente.
        self.velocidade = velocidade
        self.cor = cor

    def movimentar(self):
        # variável global - não é um atributo do objeto
        # o objeto usa para sinalizar que o jogo deve ser encerrado.
        global jogo_terminou

        # Atualizam o atributo "posicao"
        self.posicao[0] += self.velocidade[0]
        self.posicao[1] += self.velocidade[1]

        # Regra para verificar se o jogo terminou.
        # no caso desse exemplo, assim que uma nave saí
        # para fora da área do jogo em algumas direções específicas:

        if self.posicao[0] > largura or self.posicao[1] > altura:
             jogo_terminou = True

    # Método que recebe um parâmetro externo ao objeto
    def desenha(self, tela):
        # chama uma função na biblioteca para desenhar um retângulo
        # na posição indicada pelos atributos da própria nave;
        pygame.draw.rect(tela, self.cor, (self.posicao[0], self.posicao[1], 50, 50))


def principal():

    global jogo_terminou

    # chama o pygame para criar uma janela onde o jogo se desenrola:
    tela = pygame.display.set_mode((largura, altura))
    # note que essa função do Pygame também retornar um "objeto".
    # no caso é um objeto do tipo "Surface", que corresponde
    # à janela do jogo, que também tem métodos e atributos
    # que podemos usar.

    jogo_terminou = False

    # cria um objeto do tipo nave, com uma posicao, velocidae e cores definidas
    nave1 = Nave(posicao=(0, 0), velocidade=(10, 5), cor=(255,0,0))

    # A posicao e velocidade são passadas como uma sequência numérica de dois numeros,
    # onde o primeiro corresponde à coordenada horizontal, e o segundo à coordenad vertical.
    # Num exemplo maior, poderiamos criar uma classe específica "vetor" para
    # passar esses dados.

    # Já as cores são passadas como uma sequência de três números entre 0 e 255,
    # correspondendo ao vermelho, verde e azul da cor. Essa é uma convenção
    # do pygame, que faz muito sentido quando trabalhamos com imagens

    # cria _outro_ objeto do tipo nave, em outra posição, etc...
    nave2 = Nave(posicao=(largura, 0), velocidade=(-10, 10), cor=(0,0,255))

    # laço principal do jogo -
    # num jogo completo, aqui entraria o código
    # para verificar teclas oressionadas,
    # movimentação do mouse, etc....
    while not jogo_terminou:

        # chama o método movimentar de cada uma das naves.
        nave1.movimentar()
        nave2.movimentar()

        # chama o método do objeto da classe "Surface" do pygame que
        # preenche toda a área com uma única cor (no caso, preto)
        tela.fill((0,0,0))

        # Chama os métodos para cada nave desenhar a si mesma na tela.
        nave1.desenha(tela)
        nave2.desenha(tela)

        # Uma função especial do pygame que sincroniza o que se vê na janela
        # com o que foi atualizado na memória, com as chamadas acima.
        pygame.display.flip()
        # Uma função do pygame para fazer uma pausa de 100 milisegundos
        # antes de repetir as atualizações das naves.
        pygame.time.delay(100)

    # Funçao do pygame para encerrar a janela e outros objetos internos
    pygame.quit()

# chama a nossa funçao principal, que coordena todo o programa:
principal()

This code works and will show the ships, drawn as rectangles, moving on the screen at the same time, and ending when one of them left the field of view. To run it, in your Python 3 install pygame (www.pygame.org) - if you have "Pip" working, just type pip install pygame. Otherwise, on Linux, something like sudo apt-get install python3-pygame, for Windows, I believe there should be some installer on the site.


Returning the cold cow, other examples of objects,, in another context, could be a bank account, which would have as attributes "balance", "cpf_do_holder" and "limit" for example.

The form terminology of object orientation adds other formal terms, and the thing may seem complex - you will see terms like "encapsulation", "messages", etc..., but the ones you asked are the ones that have a very concrete representation in Python code and are exemplified above. Some of these concepts may be abstract, and they are easier to understand, in my view, once you have a more concrete notion like the one I try to pass on in this example. And in particular here we leave out the concept of "heritage", which some books and texts like to present at once.

  • I believe this topic is the closest to ideal to raise my doubt (but if I think it is not possible to answer here), I will consider opening a specific question. In the video The art of subclassing, of Raymond Hettinger, he puts that Python has its implementation somewhat different from concept defined by OOP; that in Python, classes are considered function dictionaries and that would be correct create subclasses only to reuse code, not to define a specialization only. This would change something in your definition?

  • In the slide that I mentioned in the link, it even defines the contrast between the operational view and the conceptual view. It is quite common to see in almost all materials, even in Python, address the definitions of conceptual view, but by implementing Python to go further to the operational view, it would not be correct to say that the Python OO runs a little, so to speak, the conceptual definitions of OO itself?

  • Well, I don’t know if I let it out enough in the last paragraph, but I don’t really like academics, which I consider exaggerated around some things (and it took place where I worked where I was considered "the boring academician"). I’ll need to see the slides and these settings to answer more properly. But in Python, one thing is certain: "practicality beats purism". I think it’s worth a separate question yes.

2

Class

Structure containing behaviors and characteristics (methods and attributes). (Read more)

class Pessoa:
    def __init__(self, nome, idade):
        self.nome = nome
        self.idade = idade

    def get_info(self):
        return "%s tem %s anos" % (self.nome, self.idade)

Object

Object is what receives the instance of a class. See the case below, instantiating the class previously created and attributing to the p1. This P1 variable will inherit all attributes and methods of the class.

...
p1 = Pessoa("Guilherme", 21)
p1.get_info()

Attribute

Class attributes are variables created within Classes. (Example Class) (Read more)

 self.nome = nome
 self.idade = idade

Method

Methods are functions within a class that are also inherited by objects, when instantiated. (Class). (Read more)

def funcao_sem_retorno():
    print("Só to aqui pra dar um oi")

def retornar_calculo_complexo(a, b):
    return a + b

print( funcao_sem_retorno() )

resultado = retornar_calculo_complexo(1, 1)
print( resultado )

A great source for studies: Python Object Oriented Programming

  • 2

    Hi William - sorry, but this answer has several conceptual errors - so I have to downvote. In particular a Python "object" is not a dictionary. In javascript the two things are equivalent, but in Python they are well different. Your attribute and method definitions also are wrong, and class though not wrong clings to the form of the statement, and not to the meaning of what is "to be" a class.

  • I edited it there. I really mistook Javascript for objects and dictionaries. I made some changes, the idea is to be a simple and objective answer. Without much text and lero lero, this can take away the will of the reader to want to understand. Abs and thanks for the feedback.

Browser other questions tagged

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