相关疑难解决方法(0)

我应该如何在Python中声明实例变量的默认值?

我应该给我的班级成员默认值如下:

class Foo:
    num = 1
Run Code Online (Sandbox Code Playgroud)

或者像这样?

class Foo:
    def __init__(self):
        self.num = 1
Run Code Online (Sandbox Code Playgroud)

这个问题中,我发现在这两种情况下,

bar = Foo()
bar.num += 1
Run Code Online (Sandbox Code Playgroud)

是一个定义明确的操作.

我知道第一种方法会给我一个类变量,而第二种方法则不会.但是,如果我不需要类变量,但只需要为我的实例变量设置默认值,这两种方法同样好吗?或者其中一个比另一个更'pythonic'?

我注意到的一件事是,在Django教程中,他们使用第二种方法来声明模型.我个人认为第二种方法更优雅,但我想知道"标准"方式是什么.

python oop class

80
推荐指数
3
解决办法
8万
查看次数

为什么我的类没有通过“def __int__”或“def _init_”初始化?为什么我会收到“不带参数”类型错误或属性错误?

如果您的问题作为此问题的重复项而被关闭,那是因为您有一个代码示例,其中包含以下任一内容:

class Example:
    def __int__(self, parameter):
        self.attribute = parameter
Run Code Online (Sandbox Code Playgroud)

或者:

class Example:
    def _init_(self, parameter):
        self.attribute = parameter
Run Code Online (Sandbox Code Playgroud)

当您随后尝试创建该类的实例时,会发生错误:

>>> Example("an argument")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Example() takes no arguments
Run Code Online (Sandbox Code Playgroud)

(在某些版本的 Python 中,错误可能会显示TypeError: object.__new__() takes no parameters。)

或者,该类的实例似乎缺少属性:

>>> class Example:
...     def __int__(self): # or _init_
...         self.attribute = 'value'

>>> Example().attribute
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Example' object has no …
Run Code Online (Sandbox Code Playgroud)

python initialization class typeerror magic-methods

11
推荐指数
1
解决办法
5733
查看次数

标签 统计

class ×2

python ×2

initialization ×1

magic-methods ×1

oop ×1

typeerror ×1