Class name error python

Here is Python "TypeError: Name() takes no arguments" solution. This error occurs when we forget, misspell, or define __init__() with no arguments. Read More »

In Python, we use the class keyword to create a blueprint for an object. And inside the class, we can define a special method

__init__(self)

which is the constructor of the class, and get automatically called when we create the class object. If we misspell, forget, or define the __init__() method with no argument, and create a class object by specifying the initial value. We will encounter the error

TypeError: ClassName() takes no arguments

Error.

In this Python guide, we will discuss the

TypeError: ClassName() takes no arguments

Error in Detail and see the different scenarios when you may encounter this error in your Python program.



Let’s


get started with the error statement


Python Error: TypeError: ClassName() takes no arguments

The Error statement

TypeError: ClassName() takes no arguments

can be divided into two parts,

Exception Type (

TypeError

)

and

Error Message (

ClassName() takes no arguments

).


1. TypeError

TypeError is a standard Python exception. It is raised in a Python program when we perform an invalid operation or function on a Python object. For example, passing argument value to a function or method that accepts no arguments will raise the TypeError with a specific Error Message.


2. ClassName() takes no arguments


ClassName() takes no arguments

is the Error message telling us that the class ClassName()

__init__()

method does not accept any argument value. When we initialize an object for a class, the

__init__()

method gets invoked automatically. If we have defined some parameters for the

__init__()

method in the class definition, we can pass argument values for those parameters during object initialization.

This Error generally occurs in a Python program when we create an object for a class and pass an argument value to the

__init__()

method where the

__init__()

method is not defined or accepts no argument.


Example Scenario

There could be two scenarios where you may encounter this error.

  1. Forget to define a

    __init__(self)

    method and create an object by passing arguments.
  2. Misspelled the

    __init__(self)

    method.


Example 1 (Forget to define __init__(self) method)



__init__()


is a special method. It is the constructor for the class and gets called when we initialize an instance or object for the Class. It is not necessary to define the

__init__()

method for a class, but if we wish to initialize some initial values to a class object, there we need to specify the

__init__()

method.

If we forget to define the

__init__()

method and try to initialize the class object with some argument values we will receive the

TypeError: ClassName() takes no arguments

Error.


Example 1

# create a class
class Student:
    # forget to define the __init__() method

    def show_marks(self):
        print(f"Total Marks of {self.name} are {self.marks}")

    def show_details(self):
        print("Name: ", self.name)
        print("Age: ", self.age)
        print("Grade: ", self.grade)
        print("Total Marks: ", self.marks)

#
name, age , grade, marks = ["Rahul Kumar", 17, "11th", 893]

# create an object
rahul = Student(name, age, grade, marks)


Output

Traceback (most recent call last):
  File "main.py", line 19, in 
    rahul = Student(name, age, grade, marks)
TypeError: Student() takes no arguments


Break the code

In this example, we are getting this error because, at object creation, we are passing 4 arguments value

name, age, grade, marks

to the

Student()

class, which is supposed to accept by the

__init__()

method.

By default, every time we define a class and create its object, Python automatically creates the

__init__()

method for that object. But that automatically created

__init__(self)

method does not accept any argument value. So if we want to initialize some initial values to object properties, we need to define the

__init__()

method in our class and specify the parameters. So it can accept all the argument values assigned during the object creation.


Solution

To solve the above problem, all we need to do is define the __init__() method for the class Student and define the 4 parameters for 4 argument values name, age, grade, and marks.

# create a class
class Student:
    # define the __init__() method
    def __init__(self, name, age, grade, marks):
        self.name = name
        self.age = age
        self.grade = grade
        self.marks = marks

    def show_marks(self):
        print(f"Total Marks of {self.name} are {self.marks}")

    def show_details(self):
        print("Name: ", self.name)
        print("Age: ", self.age)
        print("Grade: ", self.grade)
        print("Total Marks: ", self.marks)

#
name, age , grade, marks = ["Rahul Kumar", 17, "11th", 893]

# create an object
rahul = Student(name, age, grade, marks)

rahul.show_details()


Example 2 (Misspelt the __init__(self) method)

The method calling is similar to the function call. The same goes for the invoking of the

__init__()

method. As we do not call the

__init__()

method explicitly, it gets automatically called when we initialize the class object. Here the thing to keep in mind is that the

__init__()

is a reserved method, and when we use it in our class, we are just overriding the default __init__() method.

If during defining a __init__() method if we misspelled it, that method will be treated as a completely different method, and it will be assumed that the class has no __init__() method.


Example 2

# create a class
class Student:
    # misspell the __init__() method
    def __inti__(self, name, age, grade, marks):
        self.name = name
        self.age = age
        self.grade = grade
        self.marks = marks

    def show_marks(self):
        print(f"Total Marks of {self.name} are {self.marks}")

    def show_details(self):
        print("Name: ", self.name)
        print("Age: ", self.age)
        print("Grade: ", self.grade)
        print("Total Marks: ", self.marks)

#
name, age , grade, marks = ["Rahul Kumar", 17, "11th", 893]

# initialize an object
rahul = Student(name, age, grade, marks)

rahul.show_details()


Output

Traceback (most recent call last):
    File "main.py", line 25, in <module>
        rahul = Student(name, age, grade, marks)
TypeError: Student() takes no arguments


Break the code

In this example, we are getting the same error statement as we are receiving in the above example. If we analyze the code carefully, we will conclude that the core reason for this error is the same for both of the examples (Example 1 and Example 2).

Even in this example, there is no

__init__()

method that is supposed to invoke and accept the argument sent by the object during object initialization. Although the mistake is completely different here, we have tried to define the

__init__()

method, but we misspelled it.


Solution

To solve the above example, all we need to do is correct the spelling of

__init__()

method. Becaue Python is a case-sensitive programming language.

# create a class
class Student:
    # correct the __init__() method
    def __init__(self, name, age, grade, marks):
        self.name = name
        self.age = age
        self.grade = grade
        self.marks = marks

    def show_marks(self):
        print(f"Total Marks of {self.name} are {self.marks}")

    def show_details(self):
        print("Name: ", self.name)
        print("Age: ", self.age)
        print("Grade: ", self.grade)
        print("Total Marks: ", self.marks)

#
name, age , grade, marks = ["Rahul Kumar", 17, "11th", 893]

# initialize an object
rahul = Student(name, age, grade, marks)

rahul.show_details()


Output

Name: Rahul Kumar
Age: 17
Grade: 11th
Total Marks: 893


Conclusion

The Python Error «TypeError: Name() takes no arguments» is raised when we forget to define the __init__() method or misspell it, and we try to pass some argument values to the init method during object initialization. It is not necessary that if you do not define or misspell the

__init__()

method and you will encounter this error. You will only encounter this error when you pass some initial argument values to the object during object creation, and there is no __init__() method defined in the class that can accept all those arguments.

If you are getting this error in your Python program, you can share your code in the comment section. We will try to help you in debugging.


People are also reading:

  • Python typeerror: ‘str’ object is not callable Solution

  • How to Convert Python Files into Executables Standalone File?

  • Python TypeError: ‘method’ object is not subscriptable Solution

  • File I/O in Python

  • Python ValueError: invalid literal for int() with base 10: Solution

  • Move File in Python: A Complete Guide

  • Python TypeError: ‘function’ object is not subscriptable Solution

  • Read File in Python

  • Python SyntaxError: unexpected EOF while parsing Solution

  • How to Download Files in Python?

Обработка ошибок увеличивает отказоустойчивость кода, защищая его от потенциальных сбоев, которые могут привести к преждевременному завершению работы.

Синтаксис обработки исключений

Прежде чем переходить к обсуждению того, почему обработка исключений так важна, и рассматривать встроенные в Python исключения, важно понять, что есть тонкая грань между понятиями ошибки и исключения.

Ошибку нельзя обработать, а исключения Python обрабатываются при выполнении программы. Ошибка может быть синтаксической, но существует и много видов исключений, которые возникают при выполнении и не останавливают программу сразу же. Ошибка может указывать на критические проблемы, которые приложение и не должно перехватывать, а исключения — состояния, которые стоит попробовать перехватить. Ошибки — вид непроверяемых и невозвратимых ошибок, таких как OutOfMemoryError, которые не стоит пытаться обработать.

Обработка исключений делает код более отказоустойчивым и помогает предотвращать потенциальные проблемы, которые могут привести к преждевременной остановке выполнения. Представьте код, который готов к развертыванию, но все равно прекращает работу из-за исключения. Клиент такой не примет, поэтому стоит заранее обработать конкретные исключения, чтобы избежать неразберихи.

Ошибки могут быть разных видов:

  • Синтаксические
  • Недостаточно памяти
  • Ошибки рекурсии
  • Исключения

Разберем их по очереди.

Синтаксические ошибки (SyntaxError)

Синтаксические ошибки часто называют ошибками разбора. Они возникают, когда интерпретатор обнаруживает синтаксическую проблему в коде.

Рассмотрим на примере.

a = 8
b = 10
c = a b
File "", line 3
 c = a b
       ^
SyntaxError: invalid syntax

Стрелка вверху указывает на место, где интерпретатор получил ошибку при попытке исполнения. Знак перед стрелкой указывает на причину проблемы. Для устранения таких фундаментальных ошибок Python будет делать большую часть работы за программиста, выводя название файла и номер строки, где была обнаружена ошибка.

Недостаточно памяти (OutofMemoryError)

Ошибки памяти чаще всего связаны с оперативной памятью компьютера и относятся к структуре данных под названием “Куча” (heap). Если есть крупные объекты (или) ссылки на подобные, то с большой долей вероятности возникнет ошибка OutofMemory. Она может появиться по нескольким причинам:

  • Использование 32-битной архитектуры Python (максимальный объем выделенной памяти невысокий, между 2 и 4 ГБ);
  • Загрузка файла большого размера;
  • Запуск модели машинного обучения/глубокого обучения и много другое;

Обработать ошибку памяти можно с помощью обработки исключений — резервного исключения. Оно используется, когда у интерпретатора заканчивается память и он должен немедленно остановить текущее исполнение. В редких случаях Python вызывает OutofMemoryError, позволяя скрипту каким-то образом перехватить самого себя, остановить ошибку памяти и восстановиться.

Но поскольку Python использует архитектуру управления памятью из языка C (функция malloc()), не факт, что все процессы восстановятся — в некоторых случаях MemoryError приведет к остановке. Следовательно, обрабатывать такие ошибки не рекомендуется, и это не считается хорошей практикой.

Ошибка рекурсии (RecursionError)

Эта ошибка связана со стеком и происходит при вызове функций. Как и предполагает название, ошибка рекурсии возникает, когда внутри друг друга исполняется много методов (один из которых — с бесконечной рекурсией), но это ограничено размером стека.

Все локальные переменные и методы размещаются в стеке. Для каждого вызова метода создается стековый кадр (фрейм), внутрь которого помещаются данные переменной или результат вызова метода. Когда исполнение метода завершается, его элемент удаляется.

Чтобы воспроизвести эту ошибку, определим функцию recursion, которая будет рекурсивной — вызывать сама себя в бесконечном цикле. В результате появится ошибка StackOverflow или ошибка рекурсии, потому что стековый кадр будет заполняться данными метода из каждого вызова, но они не будут освобождаться.

def recursion():
    return recursion()

recursion()
---------------------------------------------------------------------------

RecursionError                            Traceback (most recent call last)

 in 
----> 1 recursion()


 in recursion()
      1 def recursion():
----> 2     return recursion()


... last 1 frames repeated, from the frame below ...


 in recursion()
      1 def recursion():
----> 2     return recursion()


RecursionError: maximum recursion depth exceeded

Ошибка отступа (IndentationError)

Эта ошибка похожа по духу на синтаксическую и является ее подвидом. Тем не менее она возникает только в случае проблем с отступами.

Пример:

for i in range(10):
    print('Привет Мир!')
  File "", line 2
    print('Привет Мир!')
        ^
IndentationError: expected an indented block

Исключения

Даже если синтаксис в инструкции или само выражение верны, они все равно могут вызывать ошибки при исполнении. Исключения Python — это ошибки, обнаруживаемые при исполнении, но не являющиеся критическими. Скоро вы узнаете, как справляться с ними в программах Python. Объект исключения создается при вызове исключения Python. Если скрипт не обрабатывает исключение явно, программа будет остановлена принудительно.

Программы обычно не обрабатывают исключения, что приводит к подобным сообщениям об ошибке:

Ошибка типа (TypeError)

a = 2
b = 'PythonRu'
a + b
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
      1 a = 2
      2 b = 'PythonRu'
----> 3 a + b


TypeError: unsupported operand type(s) for +: 'int' and 'str'

Ошибка деления на ноль (ZeroDivisionError)

10 / 0
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

 in 
----> 1 10 / 0


ZeroDivisionError: division by zero

Есть разные типы исключений в Python и их тип выводится в сообщении: вверху примеры TypeError и ZeroDivisionError. Обе строки в сообщениях об ошибке представляют собой имена встроенных исключений Python.

Оставшаяся часть строки с ошибкой предлагает подробности о причине ошибки на основе ее типа.

Теперь рассмотрим встроенные исключения Python.

Встроенные исключения

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

Прежде чем переходить к разбору встроенных исключений быстро вспомним 4 основных компонента обработки исключения, как показано на этой схеме.

  • Try: он запускает блок кода, в котором ожидается ошибка.
  • Except: здесь определяется тип исключения, который ожидается в блоке try (встроенный или созданный).
  • Else: если исключений нет, тогда исполняется этот блок (его можно воспринимать как средство для запуска кода в том случае, если ожидается, что часть кода приведет к исключению).
  • Finally: вне зависимости от того, будет ли исключение или нет, этот блок кода исполняется всегда.

В следующем разделе руководства больше узнаете об общих типах исключений и научитесь обрабатывать их с помощью инструмента обработки исключения.

Ошибка прерывания с клавиатуры (KeyboardInterrupt)

Исключение KeyboardInterrupt вызывается при попытке остановить программу с помощью сочетания Ctrl + C или Ctrl + Z в командной строке или ядре в Jupyter Notebook. Иногда это происходит неумышленно и подобная обработка поможет избежать подобных ситуаций.

В примере ниже если запустить ячейку и прервать ядро, программа вызовет исключение KeyboardInterrupt. Теперь обработаем исключение KeyboardInterrupt.

try:
    inp = input()
    print('Нажмите Ctrl+C и прервите Kernel:')
except KeyboardInterrupt:
    print('Исключение KeyboardInterrupt')
else:
    print('Исключений не произошло')

Исключение KeyboardInterrupt

Стандартные ошибки (StandardError)

Рассмотрим некоторые базовые ошибки в программировании.

Арифметические ошибки (ArithmeticError)

  • Ошибка деления на ноль (Zero Division);
  • Ошибка переполнения (OverFlow);
  • Ошибка плавающей точки (Floating Point);

Все перечисленные выше исключения относятся к классу Arithmetic и вызываются при ошибках в арифметических операциях.

Деление на ноль (ZeroDivisionError)

Когда делитель (второй аргумент операции деления) или знаменатель равны нулю, тогда результатом будет ошибка деления на ноль.

try:  
    a = 100 / 0
    print(a)
except ZeroDivisionError:  
    print("Исключение ZeroDivisionError." )
else:  
    print("Успех, нет ошибок!")
Исключение ZeroDivisionError.

Переполнение (OverflowError)

Ошибка переполнение вызывается, когда результат операции выходил за пределы диапазона. Она характерна для целых чисел вне диапазона.

try:  
    import math
    print(math.exp(1000))
except OverflowError:  
    print("Исключение OverFlow.")
else:  
    print("Успех, нет ошибок!")
Исключение OverFlow.

Ошибка утверждения (AssertionError)

Когда инструкция утверждения не верна, вызывается ошибка утверждения.

Рассмотрим пример. Предположим, есть две переменные: a и b. Их нужно сравнить. Чтобы проверить, равны ли они, необходимо использовать ключевое слово assert, что приведет к вызову исключения Assertion в том случае, если выражение будет ложным.

try:  
    a = 100
    b = "PythonRu"
    assert a == b
except AssertionError:  
    print("Исключение AssertionError.")
else:  
    print("Успех, нет ошибок!")

Исключение AssertionError.

Ошибка атрибута (AttributeError)

При попытке сослаться на несуществующий атрибут программа вернет ошибку атрибута. В следующем примере можно увидеть, что у объекта класса Attributes нет атрибута с именем attribute.

class Attributes(obj):
    a = 2
    print(a)

try:
    obj = Attributes()
    print(obj.attribute)
except AttributeError:
    print("Исключение AttributeError.")

2
Исключение AttributeError.

Ошибка импорта (ModuleNotFoundError)

Ошибка импорта вызывается при попытке импортировать несуществующий (или неспособный загрузиться) модуль в стандартном пути или даже при допущенной ошибке в имени.

import nibabel
---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

 in 
----> 1 import nibabel


ModuleNotFoundError: No module named 'nibabel'

Ошибка поиска (LookupError)

LockupError выступает базовым классом для исключений, которые происходят, когда key или index используются для связывания или последовательность списка/словаря неверна или не существует.

Здесь есть два вида исключений:

  • Ошибка индекса (IndexError);
  • Ошибка ключа (KeyError);

Ошибка ключа

Если ключа, к которому нужно получить доступ, не оказывается в словаре, вызывается исключение KeyError.

try:  
    a = {1:'a', 2:'b', 3:'c'}  
    print(a[4])  
except LookupError:  
    print("Исключение KeyError.")
else:  
    print("Успех, нет ошибок!")

Исключение KeyError.

Ошибка индекса

Если пытаться получить доступ к индексу (последовательности) списка, которого не существует в этом списке или находится вне его диапазона, будет вызвана ошибка индекса (IndexError: list index out of range python).

try:
    a = ['a', 'b', 'c']  
    print(a[4])  
except LookupError:  
    print("Исключение IndexError, индекс списка вне диапазона.")
else:  
    print("Успех, нет ошибок!")
Исключение IndexError, индекс списка вне диапазона.

Ошибка памяти (MemoryError)

Как уже упоминалось, ошибка памяти вызывается, когда операции не хватает памяти для выполнения.

Ошибка имени (NameError)

Ошибка имени возникает, когда локальное или глобальное имя не находится.

В следующем примере переменная ans не определена. Результатом будет ошибка NameError.

try:
    print(ans)
except NameError:  
    print("NameError: переменная 'ans' не определена")
else:  
    print("Успех, нет ошибок!")
NameError: переменная 'ans' не определена

Ошибка выполнения (Runtime Error)

Ошибка «NotImplementedError»
Ошибка выполнения служит базовым классом для ошибки NotImplemented. Абстрактные методы определенного пользователем класса вызывают это исключение, когда производные методы перезаписывают оригинальный.

class BaseClass(object):
    """Опередляем класс"""
    def __init__(self):
        super(BaseClass, self).__init__()
    def do_something(self):
	# функция ничего не делает
        raise NotImplementedError(self.__class__.__name__ + '.do_something')

class SubClass(BaseClass):
    """Реализует функцию"""
    def do_something(self):
        # действительно что-то делает
        print(self.__class__.__name__ + ' что-то делает!')

SubClass().do_something()
BaseClass().do_something()

SubClass что-то делает!



---------------------------------------------------------------------------

NotImplementedError                       Traceback (most recent call last)

 in 
     14
     15 SubClass().do_something()
---> 16 BaseClass().do_something()


 in do_something(self)
      5     def do_something(self):
      6         # функция ничего не делает
----> 7         raise NotImplementedError(self.__class__.__name__ + '.do_something')
      8
      9 class SubClass(BaseClass):


NotImplementedError: BaseClass.do_something

Ошибка типа (TypeError)

Ошибка типа вызывается при попытке объединить два несовместимых операнда или объекта.

В примере ниже целое число пытаются добавить к строке, что приводит к ошибке типа.

try:
    a = 5
    b = "PythonRu"
    c = a + b
except TypeError:
    print('Исключение TypeError')
else:
    print('Успех, нет ошибок!')

Исключение TypeError

Ошибка значения (ValueError)

Ошибка значения вызывается, когда встроенная операция или функция получают аргумент с корректным типом, но недопустимым значением.

В этом примере встроенная операция float получат аргумент, представляющий собой последовательность символов (значение), что является недопустимым значением для типа: число с плавающей точкой.

try:
    print(float('PythonRu'))
except ValueError:
    print('ValueError: не удалось преобразовать строку в float: 'PythonRu'')
else:
    print('Успех, нет ошибок!')
ValueError: не удалось преобразовать строку в float: 'PythonRu'

Пользовательские исключения в Python

В Python есть много встроенных исключений для использования в программе. Но иногда нужно создавать собственные со своими сообщениями для конкретных целей.

Это можно сделать, создав новый класс, который будет наследовать из класса Exception в Python.

class UnAcceptedValueError(Exception):   
    def __init__(self, data):    
        self.data = data
    def __str__(self):
        return repr(self.data)

Total_Marks = int(input("Введите общее количество баллов: "))
try:
    Num_of_Sections = int(input("Введите количество разделов: "))
    if(Num_of_Sections < 1):
        raise UnAcceptedValueError("Количество секций не может быть меньше 1")
except UnAcceptedValueError as e:
    print("Полученная ошибка:", e.data)

Введите общее количество баллов: 10
Введите количество разделов: 0
Полученная ошибка: Количество секций не может быть меньше 1

В предыдущем примере если ввести что-либо меньше 1, будет вызвано исключение. Многие стандартные исключения имеют собственные исключения, которые вызываются при возникновении проблем в работе их функций.

Недостатки обработки исключений в Python

У использования исключений есть свои побочные эффекты, как, например, то, что программы с блоками try-except работают медленнее, а количество кода возрастает.

Дальше пример, где модуль Python timeit используется для проверки времени исполнения 2 разных инструкций. В stmt1 для обработки ZeroDivisionError используется try-except, а в stmt2if. Затем они выполняются 10000 раз с переменной a=0. Суть в том, чтобы показать разницу во времени исполнения инструкций. Так, stmt1 с обработкой исключений занимает больше времени чем stmt2, который просто проверяет значение и не делает ничего, если условие не выполнено.

Поэтому стоит ограничить использование обработки исключений в Python и применять его в редких случаях. Например, когда вы не уверены, что будет вводом: целое или число с плавающей точкой, или не уверены, существует ли файл, который нужно открыть.

import timeit
setup="a=0"
stmt1 = '''
try:
    b=10/a
except ZeroDivisionError:
    pass'''

stmt2 = '''
if a!=0:
    b=10/a'''

print("time=",timeit.timeit(stmt1,setup,number=10000))
print("time=",timeit.timeit(stmt2,setup,number=10000))

time= 0.003897680000136461
time= 0.0002797570000439009

Выводы!

Как вы могли увидеть, обработка исключений помогает прервать типичный поток программы с помощью специального механизма, который делает код более отказоустойчивым.

Обработка исключений — один из основных факторов, который делает код готовым к развертыванию. Это простая концепция, построенная всего на 4 блоках: try выискивает исключения, а except их обрабатывает.

Очень важно поупражняться в их использовании, чтобы сделать свой код более отказоустойчивым.

Name is not defined when calling module

Overview

Example error:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    Foo.hello()
NameError: name 'Foo' is not defined

This issue happens when you try to invoke a class within a module without specifying the module.

Initial Steps Overview

  1. Change the import to load the class directly

  2. Change the import to load the class directly

Detailed Steps

1) Change the call to reference the module

# foo.py
class Foo():
  @staticmethod
  def bar():
    print("Hello")

# main.py
import foo
Foo.bar() # NameError: name 'Foo' is not defined

Above we see that Foo.bar() doesn’t work, which is because we only have access to the module foo and not the class within it. To access this class we could instead do foo.Foo.bar(). In this case, foo is the module name and Foo is the class name.

You would have a similar problem if the casing of the class was the same as the module you would just receive a different error.

2) Change the import to load the class directly

Given the example shown in step #1, the import within main can be changed to make the call work. We simply need to use the following format from <modulename> import <classname>. So in our example, this would be:

from foo import Foo
Foo.bar() # This now works

Check Resolution

Your call now works as expected.

Further Information

  • NameError: Module ‘foo’ has no attribute ‘bar’
  • Python: Import vs From

@gerry

comments powered by

Содержание

  1. Значения исключений и ошибок в Python
  2. Синтаксические ошибки (SyntaxError)
  3. Недостаточно памяти (OutofMemoryError)
  4. Ошибка рекурсии (RecursionError)
  5. Ошибка отступа (IndentationError)
  6. Исключения
  7. Ошибка типа (TypeError)
  8. Ошибка деления на ноль (ZeroDivisionError)
  9. Встроенные исключения
  10. Ошибка прерывания с клавиатуры (KeyboardInterrupt)
  11. Стандартные ошибки (StandardError)
  12. Арифметические ошибки (ArithmeticError)
  13. Деление на ноль (ZeroDivisionError)
  14. Переполнение (OverflowError)
  15. Ошибка утверждения (AssertionError)
  16. Ошибка атрибута (AttributeError)
  17. Ошибка импорта (ModuleNotFoundError)
  18. Ошибка поиска (LookupError)
  19. Ошибка ключа
  20. Ошибка индекса
  21. Ошибка памяти (MemoryError)
  22. Ошибка имени (NameError)
  23. Ошибка выполнения (Runtime Error)
  24. Ошибка типа (TypeError)
  25. Ошибка значения (ValueError)
  26. Пользовательские исключения в Python
  27. Недостатки обработки исключений в Python
  28. Выводы!
  29. Python TypeError: Method_Name() missing 1 required positional argument: ‘self’ Solution
  30. Table of Content
  31. Python Error TypeError: Method_Name() missing 1 required positional argument: ‘self’
  32. 1. TypeError
  33. 2. Method_Name() missing 1 required positional argument: ‘self’
  34. Common Example Scenario
  35. 1. Calling a method using a Class Name
  36. 2. Incorrect Initialization of class Object
  37. Wrapping Up!

Значения исключений и ошибок в Python

Обработка ошибок увеличивает отказоустойчивость кода, защищая его от потенциальных сбоев, которые могут привести к преждевременному завершению работы.

Прежде чем переходить к обсуждению того, почему обработка исключений так важна, и рассматривать встроенные в Python исключения, важно понять, что есть тонкая грань между понятиями ошибки и исключения.

Ошибку нельзя обработать, а исключения Python обрабатываются при выполнении программы. Ошибка может быть синтаксической, но существует и много видов исключений, которые возникают при выполнении и не останавливают программу сразу же. Ошибка может указывать на критические проблемы, которые приложение и не должно перехватывать, а исключения — состояния, которые стоит попробовать перехватить. Ошибки — вид непроверяемых и невозвратимых ошибок, таких как OutOfMemoryError , которые не стоит пытаться обработать.

Обработка исключений делает код более отказоустойчивым и помогает предотвращать потенциальные проблемы, которые могут привести к преждевременной остановке выполнения. Представьте код, который готов к развертыванию, но все равно прекращает работу из-за исключения. Клиент такой не примет, поэтому стоит заранее обработать конкретные исключения, чтобы избежать неразберихи.

Ошибки могут быть разных видов:

  • Синтаксические
  • Недостаточно памяти
  • Ошибки рекурсии
  • Исключения

Разберем их по очереди.

Синтаксические ошибки (SyntaxError)

Синтаксические ошибки часто называют ошибками разбора. Они возникают, когда интерпретатор обнаруживает синтаксическую проблему в коде.

Рассмотрим на примере.

Стрелка вверху указывает на место, где интерпретатор получил ошибку при попытке исполнения. Знак перед стрелкой указывает на причину проблемы. Для устранения таких фундаментальных ошибок Python будет делать большую часть работы за программиста, выводя название файла и номер строки, где была обнаружена ошибка.

Недостаточно памяти (OutofMemoryError)

Ошибки памяти чаще всего связаны с оперативной памятью компьютера и относятся к структуре данных под названием “Куча” ( heap ). Если есть крупные объекты (или) ссылки на подобные, то с большой долей вероятности возникнет ошибка OutofMemory . Она может появиться по нескольким причинам:

  • Использование 32-битной архитектуры Python (максимальный объем выделенной памяти невысокий, между 2 и 4 ГБ);
  • Загрузка файла большого размера;
  • Запуск модели машинного обучения/глубокого обучения и много другое;

Обработать ошибку памяти можно с помощью обработки исключений — резервного исключения. Оно используется, когда у интерпретатора заканчивается память и он должен немедленно остановить текущее исполнение. В редких случаях Python вызывает OutofMemoryError , позволяя скрипту каким-то образом перехватить самого себя, остановить ошибку памяти и восстановиться.

Но поскольку Python использует архитектуру управления памятью из языка C (функция malloc() ), не факт, что все процессы восстановятся — в некоторых случаях MemoryError приведет к остановке. Следовательно, обрабатывать такие ошибки не рекомендуется, и это не считается хорошей практикой.

Ошибка рекурсии (RecursionError)

Эта ошибка связана со стеком и происходит при вызове функций. Как и предполагает название, ошибка рекурсии возникает, когда внутри друг друга исполняется много методов (один из которых — с бесконечной рекурсией), но это ограничено размером стека.

Все локальные переменные и методы размещаются в стеке. Для каждого вызова метода создается стековый кадр (фрейм), внутрь которого помещаются данные переменной или результат вызова метода. Когда исполнение метода завершается, его элемент удаляется.

Чтобы воспроизвести эту ошибку, определим функцию recursion , которая будет рекурсивной — вызывать сама себя в бесконечном цикле. В результате появится ошибка StackOverflow или ошибка рекурсии, потому что стековый кадр будет заполняться данными метода из каждого вызова, но они не будут освобождаться.

Ошибка отступа (IndentationError)

Эта ошибка похожа по духу на синтаксическую и является ее подвидом. Тем не менее она возникает только в случае проблем с отступами.

Исключения

Даже если синтаксис в инструкции или само выражение верны, они все равно могут вызывать ошибки при исполнении. Исключения Python — это ошибки, обнаруживаемые при исполнении, но не являющиеся критическими. Скоро вы узнаете, как справляться с ними в программах Python. Объект исключения создается при вызове исключения Python. Если скрипт не обрабатывает исключение явно, программа будет остановлена принудительно.

Программы обычно не обрабатывают исключения, что приводит к подобным сообщениям об ошибке:

Ошибка типа (TypeError)

Ошибка деления на ноль (ZeroDivisionError)

Есть разные типы исключений в Python и их тип выводится в сообщении: вверху примеры TypeError и ZeroDivisionError . Обе строки в сообщениях об ошибке представляют собой имена встроенных исключений Python.

Оставшаяся часть строки с ошибкой предлагает подробности о причине ошибки на основе ее типа.

Теперь рассмотрим встроенные исключения Python.

Встроенные исключения

Прежде чем переходить к разбору встроенных исключений быстро вспомним 4 основных компонента обработки исключения, как показано на этой схеме.

  • Try : он запускает блок кода, в котором ожидается ошибка.
  • Except : здесь определяется тип исключения, который ожидается в блоке try (встроенный или созданный).
  • Else : если исключений нет, тогда исполняется этот блок (его можно воспринимать как средство для запуска кода в том случае, если ожидается, что часть кода приведет к исключению).
  • Finally : вне зависимости от того, будет ли исключение или нет, этот блок кода исполняется всегда.

В следующем разделе руководства больше узнаете об общих типах исключений и научитесь обрабатывать их с помощью инструмента обработки исключения.

Ошибка прерывания с клавиатуры (KeyboardInterrupt)

Исключение KeyboardInterrupt вызывается при попытке остановить программу с помощью сочетания Ctrl + C или Ctrl + Z в командной строке или ядре в Jupyter Notebook. Иногда это происходит неумышленно и подобная обработка поможет избежать подобных ситуаций.

В примере ниже если запустить ячейку и прервать ядро, программа вызовет исключение KeyboardInterrupt . Теперь обработаем исключение KeyboardInterrupt .

Стандартные ошибки (StandardError)

Рассмотрим некоторые базовые ошибки в программировании.

Арифметические ошибки (ArithmeticError)

  • Ошибка деления на ноль (Zero Division);
  • Ошибка переполнения (OverFlow);
  • Ошибка плавающей точки (Floating Point);

Все перечисленные выше исключения относятся к классу Arithmetic и вызываются при ошибках в арифметических операциях.

Деление на ноль (ZeroDivisionError)

Когда делитель (второй аргумент операции деления) или знаменатель равны нулю, тогда результатом будет ошибка деления на ноль.

Переполнение (OverflowError)

Ошибка переполнение вызывается, когда результат операции выходил за пределы диапазона. Она характерна для целых чисел вне диапазона.

Ошибка утверждения (AssertionError)

Когда инструкция утверждения не верна, вызывается ошибка утверждения.

Рассмотрим пример. Предположим, есть две переменные: a и b . Их нужно сравнить. Чтобы проверить, равны ли они, необходимо использовать ключевое слово assert , что приведет к вызову исключения Assertion в том случае, если выражение будет ложным.

Ошибка атрибута (AttributeError)

При попытке сослаться на несуществующий атрибут программа вернет ошибку атрибута. В следующем примере можно увидеть, что у объекта класса Attributes нет атрибута с именем attribute .

Ошибка импорта (ModuleNotFoundError)

Ошибка импорта вызывается при попытке импортировать несуществующий (или неспособный загрузиться) модуль в стандартном пути или даже при допущенной ошибке в имени.

Ошибка поиска (LookupError)

LockupError выступает базовым классом для исключений, которые происходят, когда key или index используются для связывания или последовательность списка/словаря неверна или не существует.

Здесь есть два вида исключений:

  • Ошибка индекса ( IndexError );
  • Ошибка ключа ( KeyError );

Ошибка ключа

Если ключа, к которому нужно получить доступ, не оказывается в словаре, вызывается исключение KeyError .

Ошибка индекса

Если пытаться получить доступ к индексу (последовательности) списка, которого не существует в этом списке или находится вне его диапазона, будет вызвана ошибка индекса (IndexError: list index out of range python).

Ошибка памяти (MemoryError)

Как уже упоминалось, ошибка памяти вызывается, когда операции не хватает памяти для выполнения.

Ошибка имени (NameError)

Ошибка имени возникает, когда локальное или глобальное имя не находится.

В следующем примере переменная ans не определена. Результатом будет ошибка NameError .

Ошибка выполнения (Runtime Error)

Ошибка «NotImplementedError»
Ошибка выполнения служит базовым классом для ошибки NotImplemented . Абстрактные методы определенного пользователем класса вызывают это исключение, когда производные методы перезаписывают оригинальный.

Ошибка типа (TypeError)

Ошибка типа вызывается при попытке объединить два несовместимых операнда или объекта.

В примере ниже целое число пытаются добавить к строке, что приводит к ошибке типа.

Ошибка значения (ValueError)

Ошибка значения вызывается, когда встроенная операция или функция получают аргумент с корректным типом, но недопустимым значением.

В этом примере встроенная операция float получат аргумент, представляющий собой последовательность символов (значение), что является недопустимым значением для типа: число с плавающей точкой.

Пользовательские исключения в Python

В Python есть много встроенных исключений для использования в программе. Но иногда нужно создавать собственные со своими сообщениями для конкретных целей.

Это можно сделать, создав новый класс, который будет наследовать из класса Exception в Python.

В предыдущем примере если ввести что-либо меньше 1, будет вызвано исключение. Многие стандартные исключения имеют собственные исключения, которые вызываются при возникновении проблем в работе их функций.

Недостатки обработки исключений в Python

У использования исключений есть свои побочные эффекты, как, например, то, что программы с блоками try-except работают медленнее, а количество кода возрастает.

Дальше пример, где модуль Python timeit используется для проверки времени исполнения 2 разных инструкций. В stmt1 для обработки ZeroDivisionError используется try-except, а в stmt2 — if . Затем они выполняются 10000 раз с переменной a=0 . Суть в том, чтобы показать разницу во времени исполнения инструкций. Так, stmt1 с обработкой исключений занимает больше времени чем stmt2 , который просто проверяет значение и не делает ничего, если условие не выполнено.

Поэтому стоит ограничить использование обработки исключений в Python и применять его в редких случаях. Например, когда вы не уверены, что будет вводом: целое или число с плавающей точкой, или не уверены, существует ли файл, который нужно открыть.

Выводы!

Как вы могли увидеть, обработка исключений помогает прервать типичный поток программы с помощью специального механизма, который делает код более отказоустойчивым.

Обработка исключений — один из основных факторов, который делает код готовым к развертыванию. Это простая концепция, построенная всего на 4 блоках: try выискивает исключения, а except их обрабатывает.

Очень важно поупражняться в их использовании, чтобы сделать свой код более отказоустойчивым.

Источник

Python TypeError: Method_Name() missing 1 required positional argument: ‘self’ Solution

Vinay Khatri
Last updated on November 14, 2022

Table of Content

In Python, we first need to initialize an object for a class before we call any of the methods defined inside the class. Although we can access the class variables using the class name followed by the dot operator and variable name, if we try to access a class method using the class name, we will encounter the » TypeError: Method_Name() missing 1 required positional argument: ‘self’ » Error.

In this Error guide, we will discuss this error in detail and learn why it raises in a Python program. We will also walk through some common examples where many Python learners encounter this error.

So without further ado, let’s get started with the Error statement.

Python Error TypeError: Method_Name() missing 1 required positional argument: ‘self’

A Class is a blueprint for objects, and a class all functionalities comes into existence when we initialize its objects. If there is a method inside a class we can only call that method using the class object, not with the class name.

This is because, in Python class, all methods have a fixed argument value self (conventional name), that represents the object which is calling the method. And when we call the method using the class name we receive the error TypeError: Method_Name() missing 1 required positional argument: ‘self’ . Now let’s break the Error statement into two parts.

  1. TypeError
  2. Method_Name() missing 1 required positional argument: ‘self’

1. TypeError

TypeError is a standard Python exception, and it is raised in a Python program when we perform an operation or call a function/method on an inappropriate Python data object.

2. Method_Name() missing 1 required positional argument: ‘self’

This is the error message, which is raised in a Python program when we try to call a method using the class name. We can only call a class method using its object. All class methods have a fixed argument self , that needs to be pass to the method when the method is called. And the value of self can only be passed to the method when the method is called with the help of the class object this is because the class object is the value for the self attribute.

Common Example Scenario

There are two most common cases when you might encounter this error in Your Python program.

  1. Calling a method using Class Name
  2. Incorrect Initialization of class Object

1. Calling a method using a Class Name

The core reason why we receive this error occurs is when we use the class name to call a method rather than the object name.

Example

Output

Break the code

In the above example, we are getting this error because we are calling the show_data() method using the class name Human . When a method is invoked it expect the value for the self attribute, and it can only be satisfied when an object of the class call the method. Because the object which is calling the method becomes the value for the self attribute.

Solution To solve the above method, we first need to initialize the object for the Human class, then we can use that object name to call the show_data() method.

Output

2. Incorrect Initialization of class Object

This error also occurs when we do not properly initialize the object for a class. When we initialize or declare a class object we write the object name, followed by the assignment operator Class name and a set of parenthesis after the class name. And if we forget to put the parenthesis, it will not initialize the class instead it will provide an alternative name to the class.

Example

Output

Break the Code

In this example, we are also getting the same error. This is because in line 12 when we are initializing the object for the Human class, we forgot to put the parenthesis () after the class name » human = Human » .

The statement human = Human did not create the object human instead it simply provides the alternative name to the Human class. At this point both Human and human are the same. And we know what error occur when we call a method using the class name.

Solution

o solve the above example all we need to do is properly initialize the object for the Human class.

Output

Wrapping Up!

In this Python error we discussed one of the most common Python errors » TypeError: method_name() missing 1 required positional argument: ‘self’». This error is raised in a Python program when we call a class method with the help of the class name. To solve this error, make sure that you have initialized the class object properly before calling the method on that object. In most cases, you will be encountering this error when you haven’t declared the object correctly.

If you are still getting this error in your Python program, you can share your code and query in the comment section. We will try to help you in debugging.

People are also reading:

Источник

The Python ImportError: cannot import name error occurs when an imported class is not accessible or is in a circular dependency. 

What Causes ImportError: Cannot Import Name

This error generally occurs when a class cannot be imported due to one of the following reasons:

  • The imported class is in a circular dependency.
  • The imported class is unavailable or was not created.
  • The imported class name is misspelled.
  • The imported class from a module is misplaced.
  • The imported class is unavailable in the Python library.

Python ImportError: Cannot Import Name Example

Here’s an example of a Python ImportError: cannot import name thrown due to a circular dependency. Two python modules

test1.py and test2.py are created to achieve this:

test1.py:

from test2 import Class2
class Class1:
    obj = Class2()

test2.py:

from test1 import Class1
class Class2:
    obj = Class1()

In the above example, the initialization of obj in test1 depends on test2, and obj in test2 depends on test1. This is a circular dependency since both files attempt to load each other. Therefore, running test1.py (or test2.py) causes an ImportError: cannot import name error:

Traceback (most recent call last):
  File "test1.py", line 1, in 
    from test2 import Class2
  File "test2.py", line 1, in 
    from test1 import Class1
  File "test1.py", line 1, in 
    from test2 import Class2
ImportError: cannot import name 'Class2' from partially initialized module 'test2' (most likely due to a circular import) (test2.py)

How to Fix ImportError: Cannot Import Name in Python

The ImportError: cannot import name can be fixed using the following approaches, depending on the cause of the error:

  • If the error occurs due to a circular dependency, it can be resolved by moving the imported classes to a third file and importing them from this file.
  • If the error occurs due to a misspelled name, the name of the class in the Python file should be verified and corrected. 
  • If the imported class is unavailable or not created, the file should be checked to ensure that the imported class exists in the file. If not, it should be created.
  • If the imported class from a module is misplaced, it should be ensured that the class is imported from the correct module.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

Jun-30-2018, 11:11 AM
(This post was last modified: Jun-30-2018, 11:21 AM by python_alex.)

Hello, I am trying to learn how to create a class by following the toss coin exercise from a textbook but I kept getting the error (NameError: name Coin is not defined). I copied exactly as shown in the texbook and I am using the latest IDLE 3.65. Wonder if anyone could advise me what I did wrong or is it a version compatibility problem. Thanks.

import random

class Coin:

     def __init__(self):
          self.sideup = 'Heads'

     def toss(self):
          if random.ranint(0,1) ==0:
               self.sideup = 'Heads'
          else:
               self.sideup  = 'Tails'

     def get_sideup(self):
          return self.sideup

     def main():
          mycoin = Coin()

          print ('This side is up: ', my_coin.get_sideup())
          print ('I am tossing the coin...')
          my_coin.toss()
          print ('This side is up: ', my_coin.get_sideup())
          
     main()

Noted, thanks.

Posts: 333

Threads: 4

Joined: Jun 2018

Reputation:
24

Jun-30-2018, 12:40 PM
(This post was last modified: Jun-30-2018, 12:41 PM by gontajones.)

Pay attention at indentation of you main() function, it must be outside of the Coin class.

import random


class Coin:

    def __init__(self):
        self.sideup = 'Heads'

    def toss(self):
        # Changed to randrange(interval)
        if random.randrange(2) == 0:
            self.sideup = 'Heads'
        else:
            self.sideup = 'Tails'

    def get_sideup(self):
        return self.sideup


def main():
    # Changed to my_coin, like you call after
    my_coin = Coin()

    print('This side is up: ', my_coin.get_sideup())
    print('I am tossing the coin...')
    my_coin.toss()
    print('This side is up: ', my_coin.get_sideup())


main()

Posts: 2

Threads: 1

Joined: Jun 2018

Reputation:
0

Smile thank you so much. Was never aware that indent has an effect.

Posts: 6,572

Threads: 116

Joined: Sep 2016

Reputation:
487

(Jun-30-2018, 01:30 PM)python_alex Wrote: I am using the latest IDLE 3.65

Can show some small changes,get method removed as is not needed in Python,and trow in f-string as you use 3.6.
I don’t like the function name main() i know it’s used everywhere in Python,just give a name that fit code better.

import random

class Coin:
    def __init__(self):
        self.sideup = 'Heads'

    def toss(self):
        if random.randrange(2) == 0:
            self.sideup = 'Heads'
        else:
            self.sideup = 'Tails'

def toss_result():
    my_coin = Coin()
    print(f'This side is up: {my_coin.sideup}')
    print('I am tossing the coin...')
    my_coin.toss()
    print(f'This side is up: {my_coin.sideup}')

if __name__ == '__main__':
    toss_result()

NameErrors are one of the most common types of Python errors. When you’re first getting started, these errors can seem intimidating. They’re not too complicated. A NameError means that you’ve tried to use a variable that does not yet exist.

In this guide, we’re going to talk about the “nameerror name is not defined” error and why it is raised. We’ll walk through a few example solutions to this error to help you understand how to resolve it in your code.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

What is a NameError?

A NameError is raised when you try to use a variable or a function name that is not valid.

In Python, code runs from top to bottom. This means that you cannot declare a variable after you try to use it in your code. Python would not know what you wanted the variable to do.

The most common NameError looks like this:

nameerror name is not defined

Let’s analyze a few causes of this error.

Cause #1: Misspelled Variable or Function Name

It’s easy for humans to gloss over spelling mistakes. We can easily tell what a word is supposed to be even if it is misspelled. Python does not have this capability.

Python can only interpret names that you have spelled correctly. This is because when you declare a variable or a function, Python stores the value with the exact name you have declared.

If there is a typo anywhere that you try to reference that variable, an error will be returned.

Consider the following code snippet:

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

print(boooks)

Our code returns:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
	print(boooks)
NameError: name 'boooks' is not defined

To solve this problem, all we have to do is fix the typo. If we use “print(books)”, our code returns:

["Near Dark", "The Order", "Where the Crawdads Sing"]

If you receive a name error, you should first check to make sure that you have spelled the variable or function name correctly.

Cause #2: Calling a Function Before Declaration

Functions must be declared before they are used, like variables. This is because Python reads code from top-to-bottom. 

Let’s write a program that calls a function before it is declared:

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

print_books(books)

def print_books(books):
	for b in books:
		print(b)

Our code returns:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
	print_books(books)
NameError: name 'print_books' is not defined

We are trying to call print_books() on line three. However, we do not define this function until later in our program. To fix this error, we can move our function declaration to a place before we use it:

def print_books(books):
	for b in books:
		print(b)

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

print_books(books)

Our code returns:

Near Dark
The Order
Where the Crawdads Sing

Our code has successfully printed out the list of books.

Cause #3: Forget to Define a Variable

As programs get larger, it is easy to forget to define a variable. If you do, a name error is raised. This is because Python cannot work with variables until they are declared.

Let’s take a look at a program that prints out a list of books:

Our code returns: 

Traceback (most recent call last):
  File "main.py", line 1, in <module>
	for b in books:
NameError: name 'books' is not defined

We have not declared a variable called “books”. To solve this problem, we need to declare “books” before we use it in our code:

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

for b in books:
print(b)

Let’s try to run our program again and see what happens:

Near Dark
The Order
Where the Crawdads Sing

Now that we have defined a list of books, Python can print out each book from the list.

Cause #4: Try to Print a Single Word

To print out a word in Python, you need to surround it in either single or double quotes. This tells Python that a word is a string. If a word is not surrounded by quotes, it is treated as part of a program. Consider the following print() statement:

This code tries to print the word “Books” to the console. The code returns an error:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

Traceback (most recent call last):
  File "main.py", line 1, in <module>
	print(Books)
NameError: name 'Books' is not defined

Python treats “Books” like a variable name. To solve this error, we can enclose the word “Books” in quotation marks:

Python now knows that we want to print out a string to the console. Our new code returns: Books.

Cause #5: Declaring a Variable Out of Scope

There are two variable scopes: local and global.

Local variables are only accessible in the function or class in which they are declared. Global variables are accessible throughout a program.

If you try to access a local variable outside the scope in which it is defined, an error is raised.

The following code should print out a list of books followed by the number of books in the list:

def print_books():
  books = ["Near Dark", "The Order", "Where the Crawdads Sing"]
  for b in books:
      print(b)

print_books()
print(len(books))

Our code returns:

Near Dark
The Order
Where the Crawdads Sing
Traceback (most recent call last):
  File "main.py", line 6, in <module>
	print(len(books))
NameError: name 'books' is not defined

Our code successfully prints out the list of books. On the last line of our code, an error is returned. While we have declared the variable “books”, we only declared it inside our print_books() function. This means the variable is not accessible to the rest of our program.

To solve this problem, we can declare books in our main program. This will make it a global variable:

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

def print_books():
  for b in books:
      print(b)

print_books()
print(len(books))

Our code returns:

Near Dark
The Order
Where the Crawdads Sing
3

Our code prints out every book in the “books” list. Then, our code prints out the number of books in the list using the len() method.

Понравилась статья? Поделить с друзьями:
  • Clash of clans как изменить вид деревни
  • Clarke error grid
  • Clang fatal error iostream file not found
  • Clang error unsupported option fopenmp
  • Clang error no such file or directory