相关疑难解决方法(0)

Python __init__和self他们做了什么?

我正在学习Python编程语言,而且我遇到了一些我不太了解的东西.

在如下方法中:

def method(self, blah):
    def __init__(?):
        ....
    ....
Run Code Online (Sandbox Code Playgroud)

怎么self办?这是什么意思?这是强制性的吗?

__init__方法有什么作用?为什么有必要?(等等.)

我认为它们可能是OOP结构,但我不太了解.

python oop self

737
推荐指数
18
解决办法
102万
查看次数

为什么我的类没有通过“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
查看次数

Python:object .__ new __()不带参数

现在我正在开发一个程序,允许人们进行测试,将它们保存到数据库,然后打印它们.我一直收到错误:

Traceback (most recent call last):
File "C:/Users/Shepard/Desktop/Gradebook.py", line 50, in <module>
qs = QuestionStorage("questions.db")
TypeError: object.__new__() takes no parameters
Run Code Online (Sandbox Code Playgroud)

任何人都有任何想法?我假设它在QuestionStorage类的某个地方,但我不能完全解决任何问题.这是我第一次使用SQLite3,而且我遇到了很多麻烦,如果有人可以帮助我,那就太棒了.:)

import sqlite3
class QuestionStorage(object):
    def _init_(self, path):
        self.connection = sqlite3.connect(path)
        self.cursor = self.connection.cursor()

    def Close(self):
        self.cursor.close()
        self.connection.close()

    def CreateDb(self):
        query = """CREATE TABLE questions
                 (id INTEGER PRIMARY KEY, Question TEXT, Answer1 TEXT, Answer2 TEXT, Answer3 TEXT, Answer4 TEXT, CorrectAnswer TEXT)"""
        self.cursor.exeute(query)
        self.connection.commit()
        #self.cursor.close()

    def AddQuestion(self, Question, Answer1, Answer2, Answer3, Answer4):
        self.cursor.execute("""INSERT INTO questions
                                VALUES (?, ?, ?, ?, ?, …
Run Code Online (Sandbox Code Playgroud)

python

2
推荐指数
2
解决办法
5027
查看次数

标签 统计

python ×3

class ×1

initialization ×1

magic-methods ×1

oop ×1

self ×1

typeerror ×1