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

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

  • class
  • object
  • attribute
  • method
Author: Lucas Souza, 2017-12-05

2 answers

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 only be in Python.

I like to give examples like the one 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 have a match with something that is vivid directly on the screen. (I talk about 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 that aggregates methods and data (the attributes) that function as an independent set within your system modeling.

So, for example, in a ship shooting game, a class to dipo "NaveInimiga" may contain the attributes of "speed", "direction", "position". And the methods of" moving"," shooting "which are called as" actions " in the execution of the program.

Object

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

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

Attribute

Is a value associated with an object. If you know how to program, know variables-attributes are "variables tied to specific objects". When talking about objects, I mentioned some attributes that "ships" can have.

Method

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

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

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

Python-specific

Python differs from some other languages in that the attributes of objects in a class are not declared in the class in general - but rather, created dynamically 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 the"."as a separator, we can associate attributes to our object.

Below follows the example of a "ship" class that could be used in a game. Then follows the same class, with comments before each line describing everything.To be less abstract, I include a minimally functional program (just need to install pygame along 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 closing when one of them left the field of view. To run it, on 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 must be some installer on the site.


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

The object-oriented form terminology adds other formal terms, and the thing may seem complex - you'll see terms like "encapsulation", "messages", etc... but the ones you asked Are the ones that have a representation as well concrete in Python code and are exemplified above. Some of these concepts can be abstract, and they are easier to understand, in my view, after 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" inheritance", which some books and texts like to present at once.

 3
Author: jsbueno, 2017-12-06 13:51:07

Class

Structure that contains 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 the one that receives the instance of a class. See in the case below, instantiating the Class previously created and assigning to p1. This variable p1 will inherit all the attributes and methods of the class.

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

Attribute

The attributes of the class are the variables created within of the 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
Author: Guilherme IA, 2017-12-06 15:26:24