Error missing required argument search query

почему не выполняется метод get_related_filter в классе Money? выдает ошибку TypeError: get_related_filter() missing 1 required positional argument: 'search_query' views modelPath = 'Money.models'

почему не выполняется метод get_related_filter в классе Money? выдает ошибку TypeError: get_related_filter() missing 1 required positional argument: 'search_query'

views

modelPath = 'Money.models'
app_model = importlib.import_module(modelPath)
cls = getattr(app_model, 'Money')
related_result = cls.get_related_filter(search_query)

models

class Money(models.Model):
    money = models.DecimalField(max_digits=19, blank=True, default=0, decimal_places=2)
    prepayment = models.DecimalField(max_digits=19, blank=True, default=0, decimal_places=2)    

    def get_related_filter(sefl, search_query):
        results = super(Money, self).objects.filter(Q(money__icontains=search_query))
        return results

    def __str__(self):
        return self.money  

задан 9 апр 2021 в 22:27

JopaBoga's user avatar

2

  1. Вы написали sefl, а надо self
  2. Ну и сама ошибка: в методе get_related_filter передавать search_query не надо. Чтобы использовать search_query вам надо обратится к self:

results = super(Money, self).objects.filter(Q(money__icontains=self.search_query))

Если первый способ не сработает, можно сделать через kwargs, то есть в ваш метод get_related_filter вторым аргументом передать kwargs и указать в нём search_query:

def get_related_filter(self, kwargs):
    results = super(Money, self).objects.filter(Q(money__icontains=self.kwargs["search_query"]))
    return results

ответ дан 10 апр 2021 в 19:38

Мишаня's user avatar

МишаняМишаня

6803 серебряных знака13 бронзовых знаков

emmalee

Since you have provided an unproduced client code, I will offer you an example of a client who has commented in detail.import sys
from PyQt5.QtCore import Qt
from PyQt5.QtNetwork import QTcpSocket, QHostAddress
from PyQt5.QtWidgets import QApplication, QWidget, QTextBrowser, QTextEdit, QSplitter, QPushButton,
QHBoxLayout, QVBoxLayout
class Client(QWidget):
def init(self):
super(Client, self).init()
self.resize(500, 450)
# 1. Создайте элемент управления и завершите макет интерфейса.
# Код макета находится в функции layout_init().

self.browser = QTextBrowser(self)
self.edit = QTextEdit(self)

self.splitter = QSplitter(self)
self.splitter.setOrientation(Qt.Vertical)
self.splitter.addWidget(self.browser)
self.splitter.addWidget(self.edit)
self.splitter.setSizes([350, 100])

self.send_btn = QPushButton(‘Send’, self)
self.close_btn = QPushButton(‘Close’, self)

self.h_layout = QHBoxLayout()
self.v_layout = QVBoxLayout()

# 2. Создайте объект QTcpSocket и вызовите метод connectToHost()
# для подключения к целевому хосту на указанном порту
# (в это время будут выполнены три операции рукопожатия).
# Если клиент и сервер успешно соединены, будет подан сигнал connected()

self.sock = QTcpSocket(self)
self.sock.connectToHost(QHostAddress.LocalHost, 9090)

self.layout_init()
self.signal_init()

def layout_init(self):
self.h_layout.addStretch(1)
self.h_layout.addWidget(self.close_btn)
self.h_layout.addWidget(self.send_btn)
self.v_layout.addWidget(self.splitter)
self.v_layout.addLayout(self.h_layout)
self.setLayout(self.v_layout)

# 3. Выполните операции по подключению сигналов и слотов в функции signal_init().
# Когда пользователь закончит ввод текста в поле для редактирования текста QTextEdit,
# нажмите кнопку ‘Send’, чтобы отправить текст на сервер.
# В функции слота write_data_slot() мы сначала получаем текст в поле для редактирования текста,
# затем кодируем его и отправляем, используя метод write()
# ( нет необходимости записывать адрес назначения и порт, потому что,
# он был ранее указан с помощью метода connectToHost() )
# После отправки мы очищаем поле для редактирования текста.

def signal_init(self):
self.send_btn.clicked.connect(self.write_data_slot)

# 4. Когда пользователь нажимает кнопку закрытия,
# вызывается метод close_slot(), чтобы закрыть сокет QTcpSocket,
# и закрываем окно.
self.close_btn.clicked.connect(self.close_slot)

# Как упоминалось ранее, когда клиент и сервер успешно подключены,
# будет подключен сигнал connected.
# Мы подключаем этот сигнал к функции слота connected_slot().
self.sock.connected.connect(self.connected_slot)

# Сигнал readyRead испускается,
# когда новые данные готовы для чтения.
self.sock.readyRead.connect(self.read_data_slot)

def write_data_slot(self):
message = self.edit.toPlainText()
self.browser.append(‘Client: {}’.format(message))
datagram = message.encode() # кодируем
self.sock.write(datagram) # отправляем
self.edit.clear() # очищаем поле для редактирования текста

# В этой функции слота мы просто добавляем строку ‘Connected! Ready to chat! :)’ ,
# чтобы напомнить пользователям, что они могут общаться.
def connected_slot(self):
message = ‘Connected! Ready to chat! :)’
self.browser.append(message)

# Мы используем метод bytesAvailable(), чтобы определить, есть ли данные,
# и если это так, мы вызываем метод read(), чтобы получить данные размера bytesAvailable().
# Затем данные декодируются и отображаются на экране.
def read_data_slot(self):
while self.sock.bytesAvailable():
datagram = self.sock.read(self.sock.bytesAvailable())
message = datagram.decode()
self.browser.append(‘Server: {}’.format(message))

def close_slot(self):
self.sock.close() # закрыть сокет QTcpSocket
self.close()

def closeEvent(self, event):
self.sock.close()
event.accept()

if name == ‘main’:
app = QApplication(sys.argv)
demo = Client()
demo.show()
sys.exit(app.exec_())
Of course you can check it with your server code. I just didn’t get that line in it. # ? data = b»».decode()♪import sys
import socket
sock = socket.socket()
sock.bind((», 9090))
sock.listen(3)
conn, addr = sock.accept()
while True:
data = conn.recv(1024)
if not data:
pass
else:
print(‘client is at’, addr , data)
? data = b»».decode() # ?????????????????
_data = data.decode()
print(_data)
_data = »

? data = b»».decode()
print(‘ ============ The End !’)
#input()
But I also suggest you check my PyQt server, who also commented.import sys
from PyQt5.QtNetwork import QTcpServer, QHostAddress
from PyQt5.QtWidgets import QApplication, QWidget, QTextBrowser, QVBoxLayout
class Server(QWidget):
def init(self):
super(Server, self).init()
self.resize(500, 450)
# 1. Создайте элемент управления QTextBrowser и разместите его в макете.
self.browser = QTextBrowser(self)
self.v_layout = QVBoxLayout()
self.v_layout.addWidget(self.browser)
self.setLayout(self.v_layout)

# 2. Создайте объект QTcpServer и вызовите метод listen()
# для прослушивания указанного адреса и порта.
# Возвращает True, если умеет слушать, иначе возвращает False.
# Вы можете вызвать метод errorString(), чтобы узнать причину сбоя слушателя;

self.server = QTcpServer(self)
if not self.server.listen(QHostAddress.LocalHost, 9090):
self.browser.append(self.server.errorString())

# Всякий раз, когда от клиента поступает новый запрос на соединение,
# QTcpServer отправляет сигнал newConnection.
self.server.newConnection.connect(self.new_socket_slot)

# В функции слота new_socket_slot(), связанной с этим сигналом,
# мы вызываем метод nextPendingConnection(), чтобы получить объект QTcpSocket,
# подключенный к клиенту, и получите адрес хоста и порт,
# используемый клиентом, через метод peerAddress() и метод peerPort();
def new_socket_slot(self):
sock = self.server.nextPendingConnection()

peer_address = sock.peerAddress().toString()
peer_port = sock.peerPort()
news = ‘Connected with address {}, port {}’.format(peer_address, str(peer_port))
self.browser.append(news)

sock.readyRead.connect(lambda: self.read_data_slot(sock))
sock.disconnected.connect(lambda: self.disconnected_slot(sock))

# 3. В функции слота read_data_slot(), подключенной к сигналу readyRead,
# мы декодируем данные от клиента.
# Затем закодируйте полученные данные и вызовите метод write() для отправки данных клиенту;

def read_data_slot(self, sock):
while sock.bytesAvailable():
datagram = sock.read(sock.bytesAvailable())
message = datagram.decode()
self.browser.append(f’Пришли данные от клиента -> {message}’)

# Отправляем данные обратно клиенту
new_datagram = message.encode()
sock.write(new_datagram)

# Когда соединение закрыто, отключается сигнал.
# Когда окно клиента закрыто, соединение с сервером будет закрыто, и будет отключен сигнал.
# В функции слота disconnected_slot мы показываем на экране адрес хоста и порт,
# используемые отключенным клиентом.
# Затем вызовите метод close(), чтобы закрыть сокет.

def disconnected_slot(self, sock):
peer_address = sock.peerAddress().toString()
peer_port = sock.peerPort()
news = ‘Disconnected with address {}, port {}’.format(peer_address, str(peer_port))
self.browser.append(news)

sock.close()

if name == ‘main’:
app = QApplication(sys.argv)
demo = Server()
demo.show()
sys.exit(app.exec_())

Уведомления

  • Начало
  • » Python для новичков
  • » missing 1 required positional argument

#1 Сен. 24, 2015 14:56:12

missing 1 required positional argument

Доброго времени суток.
Код просто элементарный но я не могу понять что от меня хочет Python

# coding: utf8

user_name = input("Enter your name: ")

def print_name(user_name):
print("Привет " + user_name)

print_name()

А вот что мне выдаёт:

/usr/bin/python3.4 /home/silentstorm/PycharmProjects/my_first_app/test.py
Enter your name: Silent
Traceback (most recent call last):
File "/home/silentstorm/PycharmProjects/my_first_app/test.py", line 10, in <module>
print_name()
TypeError: print_name() missing 1 required positional argument: 'user_name'

Process finished with exit code 1

Отредактировано SilentStorm (Сен. 24, 2015 14:56:33)

Офлайн

  • Пожаловаться

#2 Сен. 24, 2015 15:22:46

missing 1 required positional argument

Отредактировано py.user.next (Сен. 24, 2015 15:23:03)

Офлайн

  • Пожаловаться

#3 Сен. 24, 2015 15:25:01

missing 1 required positional argument

Это я понял, мне PyCharm сказал что тут ошибка но я не могу догнать в чем проблема. Что именно не так?
PyCharm говорит мне что нужно переименовать элемент но как бы я его не переименовывал он все равно выдает ошибку.

Отредактировано SilentStorm (Сен. 24, 2015 15:27:00)

Офлайн

  • Пожаловаться

#4 Сен. 24, 2015 15:44:24

missing 1 required positional argument

Это строка, которую надо написать вместо последней.

Офлайн

  • Пожаловаться

#5 Сен. 24, 2015 16:36:09

missing 1 required positional argument

Спасибо большое помогло.

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » missing 1 required positional argument

We need to instantiate or call classes in Python before accessing their methods. If we try to access a class method by calling only the class name, we will raise the error “missing 1 required positional argument: ‘self’”.

This tutorial will go through the definition of the error in detail. We will go through two example scenarios of this error and learn how to solve each.


Table of contents

  • Missing 1 required positional argument: ‘self’
  • Example #1: Not Instantiating an Object
    • Solution
  • Example #2: Not Correctly Instantiating Class
    • Solution
  • Summary

Missing 1 required positional argument: ‘self’

We can think of a class as a blueprint for objects. All of the functionalities within the class are accessible when we instantiate an object of the class.

“Positional argument” means data that we pass to a function, and the parentheses () after the function name are for required arguments.

Every function within a class must have “self” as an argument. “self” represents the data stored in an object belonging to a class.

You must instantiate an object of the class before calling a class method; otherwise, self will have no value. We can only call a method using the class object and not the class name. Therefore we also need to use the correct syntax of parentheses after the class name when instantiating an object.

The common mistakes that can cause this error are:

  • Not instantiating an object of a class
  • Not correctly instantiating a class

We will go through each of the mistakes and learn to solve them.

Example #1: Not Instantiating an Object

This example will define a class that stores information about particles. We will add a function to the class. Functions within classes are called methods, and the method show_particle prints the name of the particle and its charge.

class Particle:

   def __init__(self, name, charge):

       self.name = name

       self.charge = charge

   def show_particle(self):

       print(f'The particle {self.name} has a charge of {self.charge}')

To create an object of a class, we need to have a class constructor method, __init__(). The constructor method assigns values to the data members of the class when we create an object. For further reading on the __init__ special method, go to the article: How to Solve Python TypeError: object() takes no arguments.

Let’s try to create an object and assign it to the variable muon. We can derive the muon object from the Particle class, and therefore, it has access to the Particle methods. Let’s see what happens when we call the show_particle() method to display the particle information for the muon.

muon = Particle.show_particle()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
muon = Particle.show_particle()

TypeError: show_particle() missing 1 required positional argument: 'self'

The code fails because we did not instantiate an object of Particle.

Solution

To solve this error, we have to instantiate the object before we call the method show_particle()

muon = Particle("Muon", "-1")

muon.show_particle()

If we run the code, we will get the particle information successfully printed out. This version of the code works because we first declared a variable muon, which stores the information about the particle Muon. The particle Muon has a charge of -1. Once we have an instantiated object, we can call the show_particle() method.

The particle Muon has a charge of -1

Note that when you call a method, you have to use parentheses. Using square brackets will raise the error: “TypeError: ‘method’ object is not subscriptable“.

Example #2: Not Correctly Instantiating Class

If you instantiate an object of a class but use incorrect syntax, you can also raise the “missing 1 required positional argument: ‘self’” error. Let’s look at the following example:

proton = Particle

proton.show_particle()

The code is similar to the previous example, but there is a subtle difference. We are missing parentheses! If we try to run this code, we will get the following output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
proton.show_particle()

TypeError: show_particle() missing 1 required positional argument: 'self'

Because we are missing parentheses, our Python program does not know that we want to instantiate an object of the class.

Solution

To solve this problem, we need to add parentheses after the Particle class name and the required arguments name and charge.

proton = Particle("proton", "+1")

proton.show_particle()

Once the correct syntax is in place, we can run our code successfully to get the particle information.

The particle proton has a charge of +1

Summary

Congratulations on reading to the end of this tutorial. The error “missing 1 required argument: ‘self’” occurs when you do not instantiate an object of a class before calling a class method. You can also raise this error if you use incorrect syntax to instantiate a class. To solve this error, ensure you instantiate an object of a class before accessing any of the class’ methods. Also, ensure you use the correct syntax when instantiating an object and remember to use parentheses when needed.

To learn more about Python for data science and machine learning, go to the online courses page for Python.

Have fun and happy researching!

Hi,

After installing and configuring then frontend ajax search throws error:

1 exception(s):
Exception #0 (BadMethodCallException): Missing required argument $name of SmileElasticsuiteCoreSearchRequestAggregationBucketTerm.

Exception #0 (BadMethodCallException): Missing required argument $name of SmileElasticsuiteCoreSearchRequestAggregationBucketTerm.
#0 /lib/internal/Magento/Framework/ObjectManager/Factory/Dynamic/Developer.php(82): MagentoFrameworkObjectManagerFactoryDynamicDeveloper->_resolveArguments(‘SmileElasticsu…’, Array, Array)
#1 /lib/internal/Magento/Framework/ObjectManager/ObjectManager.php(57): MagentoFrameworkObjectManagerFactoryDynamicDeveloper->create(‘SmileElasticsu…’, Array)
#2 /var/generation/Smile/ElasticsuiteCore/Search/Request/Aggregation/Bucket/TermFactory.php(43): MagentoFrameworkObjectManagerObjectManager->create(‘SmileElasticsu…’, Array)
#3 /vendor/smile/elasticsuite/src/module-elasticsuite-core/Search/Request/Aggregation/AggregationFactory.php(58): SmileElasticsuiteCoreSearchRequestAggregationBucketTermFactory->create(Array)
#4 /vendor/smile/elasticsuite/src/module-elasticsuite-core/Search/Request/Aggregation/AggregationBuilder.php(91): SmileElasticsuiteCoreSearchRequestAggregationAggregationFactory->create(‘termBucket’, Array)
#5 /vendor/smile/elasticsuite/src/module-elasticsuite-core/Search/Request/Builder.php(157): SmileElasticsuiteCoreSearchRequestAggregationAggregationBuilder->buildAggregations(Object(SmileElasticsuiteCoreSearchRequestContainerConfiguration), Array, Array)
#6 /vendor/smile/elasticsuite/src/module-elasticsuite-catalog/Model/ResourceModel/Product/Fulltext/Collection.php(486): SmileElasticsuiteCoreSearchRequestBuilder->create(2, ‘quick_search_co…’, 0, 5, Array, Array, Array, Array, Array)
#7 /vendor/smile/elasticsuite/src/module-elasticsuite-catalog/Model/ResourceModel/Product/Fulltext/Collection.php(383): SmileElasticsuiteCatalogModelResourceModelProductFulltextCollection->prepareRequest()
#8 /lib/internal/Magento/Framework/Data/Collection/AbstractDb.php(338): SmileElasticsuiteCatalogModelResourceModelProductFulltextCollection->_renderFiltersBefore()
#9 /vendor/smile/elasticsuite/src/module-elasticsuite-catalog/Model/ResourceModel/Product/Fulltext/Collection.php(419): MagentoFrameworkDataCollectionAbstractDb->_renderFilters()
#10 /app/code/Magento/Eav/Model/Entity/Collection/AbstractCollection.php(906): SmileElasticsuiteCatalogModelResourceModelProductFulltextCollection->_renderFilters()
#11 /app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php(727): MagentoEavModelEntityCollectionAbstractCollection->load(false, false)
#12 /lib/internal/Magento/Framework/Data/Collection.php(820): MagentoCatalogModelResourceModelProductCollection->load()
#13 /vendor/smile/elasticsuite/src/module-elasticsuite-catalog/Model/Autocomplete/Product/DataProvider.php(114): MagentoFrameworkDataCollection->getIterator()
#14 /app/code/Magento/Search/Model/Autocomplete.php(32): SmileElasticsuiteCatalogModelAutocompleteProductDataProvider->getItems()
#15 /app/code/Magento/Search/Controller/Ajax/Suggest.php(44): MagentoSearchModelAutocomplete->getItems()
#16 /var/generation/Magento/Search/Controller/Ajax/Suggest/Interceptor.php(24): MagentoSearchControllerAjaxSuggest->execute()
#17 /lib/internal/Magento/Framework/App/Action/Action.php(102): MagentoSearchControllerAjaxSuggestInterceptor->execute()
#18 /lib/internal/Magento/Framework/Interception/Interceptor.php(58): MagentoFrameworkAppActionAction->dispatch(Object(MagentoFrameworkAppRequestHttp))
#19 /lib/internal/Magento/Framework/Interception/Interceptor.php(138): MagentoSearchControllerAjaxSuggestInterceptor->___callParent(‘dispatch’, Array)
#20 /lib/internal/Magento/Framework/Interception/Interceptor.php(153): MagentoSearchControllerAjaxSuggestInterceptor->MagentoFrameworkInterception{closure}(Object(MagentoFrameworkAppRequestHttp))
#21 /var/generation/Magento/Search/Controller/Ajax/Suggest/Interceptor.php(39): MagentoSearchControllerAjaxSuggestInterceptor->___callPlugins(‘dispatch’, Array, Array)
#22 /lib/internal/Magento/Framework/App/FrontController.php(55): MagentoSearchControllerAjaxSuggestInterceptor->dispatch(Object(MagentoFrameworkAppRequestHttp))
#23 /lib/internal/Magento/Framework/Interception/Interceptor.php(58): MagentoFrameworkAppFrontController->dispatch(Object(MagentoFrameworkAppRequestHttp))
#24 /lib/internal/Magento/Framework/Interception/Interceptor.php(138): MagentoFrameworkAppFrontControllerInterceptor->___callParent(‘dispatch’, Array)
#25 /app/code/Magento/Store/App/FrontController/Plugin/RequestPreprocessor.php(94): MagentoFrameworkAppFrontControllerInterceptor->MagentoFrameworkInterception{closure}(Object(MagentoFrameworkAppRequestHttp))
#26 /lib/internal/Magento/Framework/Interception/Interceptor.php(135): MagentoStoreAppFrontControllerPluginRequestPreprocessor->aroundDispatch(Object(MagentoFrameworkAppFrontControllerInterceptor), Object(Closure), Object(MagentoFrameworkAppRequestHttp))
#27 /app/code/Magento/PageCache/Model/App/FrontController/BuiltinPlugin.php(69): MagentoFrameworkAppFrontControllerInterceptor->MagentoFrameworkInterception{closure}(Object(MagentoFrameworkAppRequestHttp))
#28 /lib/internal/Magento/Framework/Interception/Interceptor.php(135): MagentoPageCacheModelAppFrontControllerBuiltinPlugin->aroundDispatch(Object(MagentoFrameworkAppFrontControllerInterceptor), Object(Closure), Object(MagentoFrameworkAppRequestHttp))
#29 /lib/internal/Magento/Framework/Interception/Interceptor.php(153): MagentoFrameworkAppFrontControllerInterceptor->MagentoFrameworkInterception{closure}(Object(MagentoFrameworkAppRequestHttp))
#30 /var/generation/Magento/Framework/App/FrontController/Interceptor.php(26): MagentoFrameworkAppFrontControllerInterceptor->___callPlugins(‘dispatch’, Array, NULL)
#31 /lib/internal/Magento/Framework/App/Http.php(135): MagentoFrameworkAppFrontControllerInterceptor->dispatch(Object(MagentoFrameworkAppRequestHttp))
#32 /lib/internal/Magento/Framework/App/Bootstrap.php(258): MagentoFrameworkAppHttp->launch()
#33 /pub/index.php(37): MagentoFrameworkAppBootstrap->run(Object(MagentoFrameworkAppHttp))
#34 {main}

17.10.2017, 20:29. Показов 64056. Ответов 3


Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import datetime
 
class Pizza:
    def getIngredients(self):
        return self.ingredients
    def getExtraIngredients(self):
        return self.extra_ingredients
    def getTotalCost(self):
        return self.cost
    def getName(self):
        return self.name
    def __str__(self):
        return str(self.getName()) + 'n' + 'Ingredients: ' + str(self.getIngredients()) + 'n' + 
               'Extra Ingredients: ' + str(self.getExtraIngredients()) + 'n' + 'Cost: ' + str(self.getTotalCost())
 
class Margherita(Pizza):
    name = "Margherita"
    ingredients = ["tomate", "sheese", "olives", "basil"]
    cost = 79.0
    extra_ingredients = []
 
class Pepperoni(Pizza):
    name = "Pepperoni"
    ingredients = ["salami pepperoni", "momate", "mozzarella", "pepperoni pepper", "oregano", "Pomodoro sauce"]
    cost = 109.0
    extra_ingredients = []
 
class Carbonara(Pizza):
    name = "Carbonara"
    ingredients = ["ham", "champignon", "parmesan", "mozzarella", "tomatoes", "tomatoes",
                   "egg quail", "pepper", "Carbonara sauce"]
    cost = 106.0
    extra_ingredients = []
 
class Polo(Pizza):
    name = "Polo"
    ingredients = ["chicken fillet", "pineapple", "oregano", "mozzarella", "chili pepper", "Pomodoro sauce"]
    cost = 99.0
    extra_ingredients = []
 
class Four_cheeses(Pizza):
    name = "Four cheeses"
    ingredients = ["parmesan", "dork blue", "cheddar", "mozzarella", "pear", "Walnut", "creamy sauce"]
    cost = 119.0
    extra_ingredients = []
 
class Crispie(Pizza):
    name = "Crispie"
    ingredients = ["Chees Feta", "Cherry tomatoes", "sun-dried tomatoes", "champignon", "arugula", "basil"]
    cost = 139.0
    extra_ingredients = []
 
class Gurmeo(Pizza):
    name = "Gurmeo"
    ingredients = ["hunting sausages", "salami peperoni", "ham", "chicken fillet", "mushrooms", "oregano", "BBQ sauce"]
    cost = 139.0
    extra_ingredients = []
 
class Extra_Ingredients(Pizza):
    def __init__(self, pizza_component):
        self.pizza_component = pizza_component
    def getIngredients(self):
        return self.getIngredients()
    def getExtraIngredients(self):
        return self.getExtraIngredients() + Pizza.getExtraIngredients(self)
    def getTotalCost(self):
        return self.getTotalCost() + Pizza.getTotalCost(self)
    def getName(self):
        return self.name
 
class Cheese(Extra_Ingredients):
    name = "Cheese"
    cost = 12.0
    extra_ingredients = ["cheese"]
    def __init__(self, pizza_component):
        ExtraIngredients.__init__(self, pizza_component)
        self.pizza_component = components
 
class Tomatto(Extra_Ingredients):
    name = "Tomatto"
    cost = 8.0
    extra_ingredients =  ["tomate"]
    def __init__(self, pizza_component):
        ExtraIngredients.__init__(self, pizza_component)
        self.pizza_component = components
 
class Bacon(Extra_Ingredients):
    name = "Bacon"
    cost = 18.0
    extra_ingredients =  ["bacon"]
    def __init__(self, pizza_component):
        ExtraIngredients.__init__(self, pizza_component)
        self.pizza_component = components
 
class Pineapple(Extra_Ingredients):
    name = "Pineapple"
    cost = 17.0
    extra_ingredients = ["pineapple"]
    def __init__(self, pizza_component):
        Extra_Ingredients.__init__(self, pizza_component)
        self.pizza_component = components
 
class Salami(Extra_Ingredients):
    name = "Salami"
    cost = 15.0
    extra_ingredients = ["salami"]
    def __init__(self, pizza_component):
        Extra_Ingredients.__init__(self, pizza_component)
        self.pizza_component= components
 
today = datetime.date.today().weekday()
 
pizza_day = {0: Pizza.__str__(Margherita()),1: Pizza.__str__(Pepperoni()),
             2: Pizza.__str__(Carbonara()),3: Pizza.__str__(Polo()),
             4: Pizza.__str__(Four_cheeses()), 5: Pizza.__str__(Crispie()), 6 : Pizza.__str__(Gurmeo())}
 
print("Pizza of the day: ",pizza_day[today])
 
components = {1: Extra_Ingredients.__init__(Cheese()), 2: Extra_Ingredients.__init__(Tomatto()),
              3: Extra_Ingredients.__init__(Bacon()), 4: Extra_Ingredients.__init__(Pineapple()),
              5: Extra_Ingredients.__init__(Salami())}

Вылетает вот такая ошибка:

Код

Traceback (most recent call last):
  File "C:UsersAdminDesktoplaba_2_1.py", line 101, in <module>
    components = {1: Extra_Ingredients.__init__(Cheese()), 2: Extra_Ingredients.__init__(Tomatto()),
TypeError: __init__() missing 1 required positional argument: 'pizza_component'

Помогите разобраться

Добавлено через 45 минут
Все равно выдается такая самая ошибка

Добавлено через 17 минут

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import datetime
 
class Pizza:
    def getIngredients(self):
        return self.ingredients
    def getExtraIngredients(self):
        return self.extra_ingredients
    def getTotalCost(self):
        return self.cost
    def getName(self):
        return self.name
    def __str__(self):
        return str(self.getName()) + 'n' + 'Ingredients: ' + str(self.getIngredients()) + 'n' + 
               'Extra Ingredients: ' + str(self.getExtraIngredients()) + 'n' + 'Cost: ' + str(self.getTotalCost())
 
class Margherita(Pizza):
    name = "Margherita"
    ingredients = ["tomate", "sheese", "olives", "basil"]
    cost = 79.0
    extra_ingredients = []
 
class Pepperoni(Pizza):
    name = "Pepperoni"
    ingredients = ["salami pepperoni", "momate", "mozzarella", "pepperoni pepper", "oregano", "Pomodoro sauce"]
    cost = 109.0
    extra_ingredients = []
 
class Carbonara(Pizza):
    name = "Carbonara"
    ingredients = ["ham", "champignon", "parmesan", "mozzarella", "tomatoes", "tomatoes",
                   "egg quail", "pepper", "Carbonara sauce"]
    cost = 106.0
    extra_ingredients = []
 
class Polo(Pizza):
    name = "Polo"
    ingredients = ["chicken fillet", "pineapple", "oregano", "mozzarella", "chili pepper", "Pomodoro sauce"]
    cost = 99.0
    extra_ingredients = []
 
class Four_cheeses(Pizza):
    name = "Four cheeses"
    ingredients = ["parmesan", "dork blue", "cheddar", "mozzarella", "pear", "Walnut", "creamy sauce"]
    cost = 119.0
    extra_ingredients = []
 
class Crispie(Pizza):
    name = "Crispie"
    ingredients = ["Chees Feta", "Cherry tomatoes", "sun-dried tomatoes", "champignon", "arugula", "basil"]
    cost = 139.0
    extra_ingredients = []
 
class Gurmeo(Pizza):
    name = "Gurmeo"
    ingredients = ["hunting sausages", "salami peperoni", "ham", "chicken fillet", "mushrooms", "oregano", "BBQ sauce"]
    cost = 139.0
    extra_ingredients = []
 
class Extra_Ingredients(Pizza):
    def __init__(self, pizza_component):
        self.pizza_component = pizza_component
    def getIngredients(self):
        return self.getIngredients()
    def getExtraIngredients(self):
        return self.getExtraIngredients() + Pizza.getExtraIngredients(self)
    def getTotalCost(self):
        return self.getTotalCost() + Pizza.getTotalCost(self)
    def getName(self):
        return self.name
 
class Cheese(Extra_Ingredients):
    name = "Cheese"
    cost = 12.0
    extra_ingredients = ["cheese"]
    def __init__(self, pizza_component):
        ExtraIngredients.__init__(self, pizza_component)
        self.pizza_component = components
 
class Tomatto(Extra_Ingredients):
    name = "Tomatto"
    cost = 8.0
    extra_ingredients =  ["tomate"]
    def __init__(self, pizza_component):
        ExtraIngredients.__init__(self, pizza_component)
        self.pizza_component = components
 
class Bacon(Extra_Ingredients):
    name = "Bacon"
    cost = 18.0
    extra_ingredients =  ["bacon"]
    def __init__(self, pizza_component):
        ExtraIngredients.__init__(self, pizza_component)
        self.pizza_component = components
 
class Pineapple(Extra_Ingredients):
    name = "Pineapple"
    cost = 17.0
    extra_ingredients = ["pineapple"]
    def __init__(self, pizza_component):
        Extra_Ingredients.__init__(self, pizza_component)
        self.pizza_component = components
 
class Salami(Extra_Ingredients):
    name = "Salami"
    cost = 15.0
    extra_ingredients = ["salami"]
    def __init__(self, pizza_component):
        Extra_Ingredients.__init__(self, pizza_component)
        self.pizza_component= components
 
today = datetime.date.today().weekday()
 
pizza_day = {0: Pizza.__str__(Margherita()),1: Pizza.__str__(Pepperoni()),
             2: Pizza.__str__(Carbonara()),3: Pizza.__str__(Polo()),
             4: Pizza.__str__(Four_cheeses()), 5: Pizza.__str__(Crispie()), 6 : Pizza.__str__(Gurmeo())}
 
print("Pizza of the day: ",pizza_day[today])
 
components = {1: Extra_Ingredients.__init__(Cheese()), 2: Extra_Ingredients.__init__(Tomatto()),
              3: Extra_Ingredients.__init__(Bacon()), 4: Extra_Ingredients.__init__(Pineapple()),
              5: Extra_Ingredients.__init__(Salami())}

все равно ошибка такая же самая

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Table of Contents
Hide
  1. What is TypeError: missing 2 required positional arguments
  2. How to fix TypeError: missing 2 required positional arguments
    1. Solution 1 – Pass the required positional arguments
    2. Solution 2 – Set the default values for the arguments
  3. Conclusion

If we have a function that accepts 2 arguments, and while calling the method, if we do not pass those 2 required arguments Python interpreter will throw TypeError: missing 2 required positional arguments

In this tutorial, we will look at what exactly TypeError: missing 2 required positional arguments and how to resolve this error with examples.

Let us take a simple example to demonstrate this issue.

# Performs Sum of 2 numbers
def calculate_sum(x, y):
    return x+y

# No args are passed 
output = calculate_sum()
print("Sum of 2 numbers is ", output)

Output

TypeError: calculate_sum() missing 2 required positional arguments: 'x' and 'y'

In the above code, we have a method called calculate_sum() that takes 2 positional arguments and returns the sum of 2 numbers.

In the following statement, we call the method calculate_sum() without passing any positional arguments to the method; hence, we get the TypeError: missing 2 required positional arguments.

How to fix TypeError: missing 2 required positional arguments

There are different ways to resolve this TypeError. Let us look at each of these solutions with examples.

Solution 1 – Pass the required positional arguments

The easy way to resolve the error is to pass the necessary positional arguments to the method. Here in our example, the function takes two arguments, and we can solve them by providing the values for both x and y args, as shown below.

# Performs Sum of 2 numbers
def calculate_sum(x, y):
    return x+y

# 2 required args are passed
output = calculate_sum(5, 6)
print("Sum of 2 numbers is ", output)

Output

Sum of 2 numbers is  11

Solution 2 – Set the default values for the arguments

In Python, the function arguments can have the default values. If we call the function without passing any argument values, the default values are used instead of throwing a TypeError.

The default values are set using the assignment operator (=). The syntax will be in the form of keyword=value.

Let us see how we can implement the default values in our example and resolve the issue.

# Performs Sum of 2 numbers
def calculate_sum(x=0, y=0):
    return x+y


# No args are passed
output = calculate_sum()
print("Sum of 2 numbers is ", output)

Output

Sum of 2 numbers is  0

In the above example, we are not passing the required positional arguments to the method calculate_sum(). However, the default values we have set in the function args are taken to calculate the sum of 2 numbers.

Here you need to ensure that the default values are set only on the value types and not on the reference types.

The reference types such as Dictionary, List, Array, Tuple, Set, etc., can cause different issues, as shown below.

Notice that the method takes the empty dictionary as the default value when we do not pass any arguments.

Here both emp1 and emp2 objects hold the reference of the employee dictionary object, and changing the emp1 object will implicitly change the emp2, as demonstrated in the below code.

# Fetch Employee Details
def get_employee_details(employee={}):
    return employee


# No args are passed
emp1 = get_employee_details()
emp2 = get_employee_details()

# Since the emp1 and emp2 object holds a reference of employee object
# changing emp1 will change emp2 object implicitly.
emp1["name"] = "Chandler Bing"

print("Employee 1 details are  ", emp1)
print("Employee 2 details are  ", emp2)

Output

Employee 1 details are   {'name': 'Chandler Bing'}
Employee 2 details are   {'name': 'Chandler Bing'}

As shown below, we can fix this issue by setting the default argument to None and conditionally returning the empty dictionary if the parameter is None.

# Fetch Employee Details
def get_employee_details(employee=None):
    if (employee is None):
        employee = {}
    return employee


# No args are passed
emp1 = get_employee_details()
emp1["name"] = "Chandler Bing"
emp2 = get_employee_details()


print("Employee 1 details are  ", emp1)
print("Employee 2 details are  ", emp2)

Output

Employee 1 details are   {'name': 'Chandler Bing'}
Employee 2 details are   {}

Conclusion

The TypeError: missing 2 required positional arguments occurs if we do not pass the 2 required positional arguments while calling the function or the method.

We can resolve the issue by passing the required positional arguments to the function or by setting the default values for the arguments using the assignment operator.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

  • #1

Win 10, Python 3.7, Tkinter 8.6.8
Мне надо связать между собой две функции. Одна получает путь к файлу, вторая — проделывает с ним некие операции. Мой обычный подход для решения таких моментов привёл к указанной в теме ошибке. Привожу пример кода:

Python:

from tkinter import *
import tkinter.filedialog as fld

def select():
    path = fld.askdirectory()
    load(path)
    
def load(pather):
    print(pather+'test')

Укажите, пожалуйста, на ошибку и способ её исправления.

  • #2

Нужно приводить пример который можно скопировать и запустить чтобы увидеть ошибку. В данном случае код ничего не выдаст.
Попробовал запустить так:

Python:

import tkinter as tk
from tkinter import filedialog as fd


root = tk.Tk()


def select():
    path = fd.askdirectory()
    load(path)


def load(pather):
    print(pather + 'test')


b1 = tk.Button(root, text='Выбрать файл', command=select)
b1.pack()


root.mainloop()

ошибок не выдает.

  • #3

Нужно приводить пример который можно скопировать и запустить чтобы увидеть ошибку. В данном случае код ничего не выдаст.

Понял. Вот полный код:

Python:

from tkinter import *
import tkinter.filedialog as fld
import os as os

def select():
    if list_of_grid.size()!=0:
        list_of_grid.delete(1.0, END)
    path = fld.askdirectory()
    for nm in os.listdir(path):
        list_of_grid.insert(END,nm)
    load(path)

def select_data(event):
    list_of_data.insert(END, list_of_grid.get(list_of_grid.curselection()))

def load(pather):
    i=0
    while i<list_of_data.size():
        st_dat=list_of_data.get(i)
        print(pather+'/'+st_dat)
        i+=1


win = Tk()
win.geometry("1024x728")
list_of_grid = Listbox()
list_of_grid.place(x=5, y=5)
list_of_grid.config(width=60, height=30)
list_of_grid.bind('<Double-Button-1>', select_data)
btn_sel_grid = Button(text='Select grid')
btn_sel_grid.place(x=5, y=500)
btn_sel_grid.config(command=select)
list_of_data = Listbox()
list_of_data.place(x=400, y=5)
list_of_data.config(width=60, height=30)
btn_start = Button(text='Start')
btn_start.place(x=900, y=700)
btn_start.config(command=load)
win.mainloop()

А вот содержимое консоли:

Код:

Exception in Tkinter callback
Traceback (most recent call last):
  File "Z:anaenvsfrag5libtkinter__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: load() missing 1 required positional argument: 'pather'

  • #4

В ошибке написано что для функции load на хватает одного позиционного аргумента 'pather'. Это происходит при вызове этой функции после нажатия на кнопку start. Ошибка возникает потому что при привязке функции к кнопке не был указан аргумент:

Python:

btn_start.config(command=load)

чтобы исправить — можно привязать к кнопке вызов функции с нужным аргументом, например:

Python:

btn_start.config(command=lambda: load(fld.askdirectory()))

  • #5

В ошибке написано что для функции load на хватает одного позиционного аргумента 'pather'. Это происходит при вызове этой функции после нажатия на кнопку start. Ошибка возникает потому что при привязке функции к кнопке не был указан аргумент:

Python:

btn_start.config(command=load)

чтобы исправить — можно привязать к кнопке вызов функции с нужным аргументом, например:

Python:

btn_start.config(command=lambda: load(fld.askdirectory()))

Ок. Спасибо. Буду пробовать. Я думал, что в самой функции ошибка. Про привязку к кнопке — даже не посещало.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error missing page authorization for pro tools
  • Error missing operator comma or semicolon
  • Error missing method body or declare abstract
  • Error missing list of packages to add to your project
  • Error missing keyring cannot use cephx for authentication

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии