Is a module the same as a Python class?

Asked

Viewed 2,530 times

8

A module is the same thing as a class?

If not what are the differences? I ask this because according to the The Zen of Python, modules should be used instead of ifs.

The problem is that after researching they seemed the same.

2 answers

11


Module

Roughly a module in Python is a file with members. A module can contain classes, functions and "loose variables". Modules are organizational units and use a concept of modularization.

A module can be imported inside other modules by making all its members (import modulo) or some selected (from modulo import classe) are available.

The first way of importing only makes members available, the second way still facilitates the use by making unnecessary in most situations the explicit reference of what you are using, but can also create ambiguities. It is still possible to import all members with the second form using from modulo import *.

The name of a module is the file name without the extension .py.

There is also a set of modules organized in directories forming what is called packages (Packages).

Class

Classes serve to create types, to structure how objects will be defined. Classes have state and state-related behavior, i.e., they have properties and methods that often do related actions by manipulating existing class properties. Classes are data structures and uses a concept of object orientation.

Classes can be instantiated, that is, it is possible to create objects and save them in variables based on what was defined in it. The class is a model to be followed, it is as if it were a low plan of a house and the object will be the house built.

Technically classes can also be used as organizational units. In this case the class should not be instantiated and would probably only have class methods and static variables. But this is not the pitonic way of doing since the language allows to get the same result with modules.

The "normal" members of a class can only be accessed through an instance. They do not exist until an object is created based on the class.

Classes can have subtypes, that is, can have inheritance and create a hierarchy of types.

To use a class just call a constructor of it that gets confused with its own name:

funcionario = Funcionario("João", 2000) //está criando um objeto com base na classe Funcionario

Wikipedia article about classes.

Completion

In a certain way we can say that the modules are surnames for the classes and other members that form the same family.

Perhaps the idea that they are the same thing comes from the fact that they both have members (variables and functions) but the way they will be accessed is quite different. To facilitate understanding one can imagine a module as being a class that cannot be instantiated. In fact and in some languages the module is exactly this. It’s not quite the case of Python, but if this thinking helps more than it hinders your understanding, use it.

I don’t know where you read which modules should be used instead of ifs, This seems to make as much sense as using gasoline instead of steel to make a milkshake. In fact, this is already weird considering the title of the question that makes sense and I used it to answer it. Perhaps some comparison was made to facilitate understanding and caused more confusion.

4

Not. Module can be defined as a file that contains definitions of variables, functions and classes, create a module can be useful in situations where you need to use the same functions and/or classes in other projects without having to write them in each one.

See a demonstration:

# Modulo1  
# Define variaveis
var1 = 1
var2 = 2

# Define algumas funcoes
def ola():
    return "ola!"

def vezesquatro(numero):
    return int(numero) * 4

# Define uma classe
class Foo:
    def __init__(self):
        self.nome  = raw_input("Qual o seu nome:")
        self.idade = raw_input("Qual a sua idade:")
        self.peso  = raw_input("Qual o seu peso:")
    def info(self):
        print "O nome dele e {0}, tem {1} anos e pesa {2} quilos!".format(self.nome, self.idade, self.peso)

Save the script above as modulo1.py and create another script and execute the code:

#!/usr/bin/python

import modulo1       

print (modulo1.var1)
print (modulo1.var2)

ola = modulo1.ola()
print (ola)

quatro = modulo1.vezesquatro(10)
print ("10 x 4 = {0}".format(quatro))

f = modulo1.Foo()
f.info()

Already a class is a structure that abstracts a set of objects that defines the behavior of these through methods and the possible states of these objects through attributes.

To response from mgibsonbr in the issue below addresses this subject in a broader way.

Browser other questions tagged

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