Python中模块和类的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43183244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:36:22  来源:igfitidea点击:

Difference between Module and Class in Python

pythonclasspython-module

提问by liwevire

Can I assign value to a variable in the module. If yes, what is the difference between a class and module.

我可以为模块中的变量赋值吗?如果是,类和模块之间有什么区别。

PS: I'm a java guy. In case if its helps in way of explaining. Thanks.

PS:我是个java人。如果它有助于解释。谢谢。

采纳答案by Leonardo Chirivì

  • Module:

    A module is a file containing Python definitions and statements.

  • 模块

    模块是包含 Python 定义和语句的文件。

As the docsay.

正如医生所说。

So a module in python is simply a way to organize the code, and it contains either python classes or just functions. If you need those classes or functions in your project, you just importthem. For instance, the mathmodule in python contains just a bunch of functions, and you just call those needed (math.sin). Just have a look at this question.

因此,python 中的模块只是组织代码的一种方式,它包含 python 类或仅包含函数。如果您的项目中需要这些类或函数,您只需使用import它们。例如,mathpython 中的模块只包含一堆函数,你只需调用那些需要的 ( math.sin)。看看这个问题

On the other hand a python class is something similar to a java class, it's only structured in a slightly different way.

另一方面,python 类类似于 java 类,只是结构略有不同。

回答by Martijn Pieters

There are hugedifferences between classes and modules in Python.

Python 中的类和模块之间存在巨大差异。

Classes are blueprints that allow you to create instances with attributes and bound functionality. Classes support inheritance, metaclasses, and descriptors.

类是蓝图,允许您创建具有属性和绑定功能的实例。类支持继承、元类和描述符。

Modules can't do any of this, modules are essentially singleton instancesof an internal moduleclass, and all their globals are attributes on the moduleinstance. You can manipulate those attributes as needed (add, remove and update), but take into account that these still form the global namespace for all code defined in that module.

模块不能做任何这些,模块本质上是内部类的单例实例module,并且它们的所有全局变量都是module实例上的属性。您可以根据需要操作这些属性(添加、删除和更新),但要考虑到这些属性仍然构成该模块中定义的所有代码的全局命名空间。

From a Java perspective, classes are not all that different here. Modules can contain more than just one class however; functions and any the result of any other Python expression can be globals in a module too.

从 Java 的角度来看,类在这里并没有什么不同。然而,模块可以包含多个类;函数和任何其他 Python 表达式的结果也可以是模块中的全局变量。

So as a general ballpark guideline:

因此,作为一般的棒球场指南:

  • Use classes as blueprints for objects that model your problem domain.
  • Use modules to collect functionality into logical units.
  • 使用类作为为您的问题域建模的对象的蓝图。
  • 使用模块将功能收集到逻辑单元中。

Then store data where it makes sense to your application. Global state goes in modules (and functions and classes are just as much global state, loaded at the start). Everything else goes into other data structures, including instances of classes.

然后将数据存储在对您的应用程序有意义的地方。全局状态在模块中(函数和类也是全局状态,在开始时加载)。其他所有内容都进入其他数据结构,包括类的实例。

回答by royl8

Can I assign value to a variable in the module?
In short yes.

我可以为模块中的变量赋值吗?
总之是的。



The concept of modulerefers to a single Python file which can be imported (by importing, you have the access to the variables/methods/classes defined in that module).

的概念是module指可以导入的单个 Python 文件(通过导入,您可以访问该模块中定义的变量/方法/类)。

It is commonly discussed together with the concept package, which is a folder with __init__.py. A package can contain sub-packages or modules, and at the same time, similar to modules, can define variables/methods/classes to be imported inside its __init__.py.

它通常与概念一起讨论package,也就是文件夹与__init__.py. 一个包可以包含子包或模块,同时,与模块类似,可以定义要在其内部导入的变量/方法/类__init__.py

The purpose of having modules/packages in Python is kind of similar to having packages in Java: to contain and categorize reusable codes, to resolve naming confliction and so on.

在 Python 中拥有模块/包的目的有点类似于在 Java 中拥有包:包含和分类可重用的代码,解决命名冲突等。



Besides, Python also has a builtin class named module, just like list, tuple, dict(note that Python builtin classes do not follow the CapWords naming convention due to legacy reasons). A moduleinstance represents the module/package imported.

此外,Python 还有一个名为 的内置类module,就像list, tuple, dict(请注意,由于遗留原因,Python 内置类不遵循 CapWords 命名约定)。一个module实例代表导入的模块/包。

When you use the importstatement to import a module (single Python file) or a package (folder with __init__.py), typically
1. a new instance of moduleclass will be created
2. the classes/methods/variables you defined in that imported Python file will be added as the attributes of this moduleinstance (if it is a package, it will be the classes/methods/variables defined in __init__.pythat are added).

当您使用该import语句导入模块(单个 Python 文件)或包(带有 的文件夹__init__.py)时,通常
1.module将创建类的新实例
2. 您在该导入的 Python 文件中定义的类/方法/变量将是添加作为此module实例的属性(如果是包,则__init__.py添加其中定义的类/方法/变量)。

Therefore, since it is just an instance of moduleclass, you can assign a value to the attribute of that instance and other class instance operations.

因此,由于它只是module类的一个实例,您可以为该实例的属性和其他类实例操作赋值。

import math

print(type([1,2,3]))
print(type(math))
print(dir([1,2,3]))
print(dir(math))

console:

安慰:

<class 'list'>
<class 'module'>
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

回答by Ali Khosro

This is how I decide to organize my code in classes or modules:

这就是我决定在类或模块中组织代码的方式:

Class is supposed to be a blueprint to create (many) instances of objects based on that blueprint. Moreover, classes can have sub-classes (inheritance).

类应该是基于该蓝图创建(许多)对象实例的蓝图。此外,类可以有子类(继承)。

Therefore, if I need inheritance or (many) instantiations, I gather functions and variables under a class definition (methods and properties).

因此,如果我需要继承或(许多)实例化,我会在类定义(方法和属性)下收集函数和变量。

Otherwise, I Keep It Simple and Stupid (KISS) and use modules.

否则,我保持简单和愚蠢(KISS)并使用模块。

A good indication of a bad class (that should have been a module): you can rewrite your all your object methods and properties with class methods and class properties.

一个坏类(应该是一个模块)的一个很好的迹象:你可以用类方法和类属性重写你所有的对象方法和属性。