Method object is not subscriptable ошибка

В этой строке:

hero.coordinate = hero.step_forward

вы не вызываете метод, а записываете «ссылку» на метод в переменную. При следующей итерации цикла вы пытаетесь сделать hero.coordinate[0] по сути от ссылки на метод, о чем и говорится в ошибке. Вам просто нужно исправить данную строку на

hero.coordinate = hero.step_forward()

А вообще, по логике, метод .step_forward() должен менять координаты объекта, а не возвращать значение. Ваш код и меняет координаты объекта, и возвращает новое значение, которое вы потом еще раз записываете в поле с координатами объекта. Вам в принципе можно просто убрать return в методе step_forward() или никак не использовать значение, возвращенное из step_forward(). Вообще, лучше не менять вручную координаты объекта, обращаясь к ним снаружи, а делать это внутри методов.

Класс лучше реализовать так:

class Hero:
    def __init__(self, coordinate)
        # Если вы будете использовать один и тот же список с координатами для разных объектов, лучше при инициализации делать копию списка с помощью list
        self.coordinate = list(coordinate)

    def step_forward(self):
        self.coordinate[0] = self.coordinate[0] + 1

Тогда при создании объекта нужно будет еще указывать его координаты.

hero = Hero([0, 0])

enemy_hero = Hero([20, 0])

while True:

    distance = sqrt( (enemy_hero.coordinate[0] - hero.coordinate[0])**2 + (enemy_hero.coordinate[1] - hero.coordinate[1])**2)

    hero.step_forward()

distance тоже можно сделать методом того же класса:

class Hero:
    def __init__(self, coordinate)
        self.coordinate = list(coordinate)

    def step_forward(self):
        self.coordinate[0] = self.coordinate[0] + 1

    def distance(self, other):
        return sqrt( (other.coordinate[0] - self.coordinate[0])**2 + (other.coordinate[1] - self.coordinate[1])**2)

Тогда цикл будет выглядеть так:

while True:
    distance = hero.distance(enemy_hero)
    hero.step_forward()

When calling a method in Python, you have to use parentheses (). If you use square brackets [], you will raise the error “TypeError: ‘method’ object is not subscriptable”.

This tutorial will describe in detail what the error means. We will explore an example scenario that raises the error and learn how to solve it.

Table of contents

  • TypeError: ‘method’ object is not subscriptable
  • Example: Calling A Method With Square Brackets
    • Solution
  • Summary

TypeError: ‘method’ object is not subscriptable

TypeErrror occurs when you attempt to perform an illegal operation for a particular data type. The part “‘method’ object is not subscriptable” tells us that method is not a subscriptable object. Subscriptable objects have a __getitem__ method, and we can use __getitem__ to retrieve individual items from a collection of objects contained by a subscriptable object. Examples of subscriptable objects are lists, dictionaries and tuples. We use square bracket syntax to access items in a subscriptable object. Because methods are not subscriptable, we cannot use square syntax to access the items in a method or call a method.

Methods are not the only non-subscriptable object. Other common “not subscriptable” errors are:

  • “TypeError: ‘float’ object is not subscriptable“,
  • “TypeError: ‘int’ object is not subscriptable“
  • “TypeError: ‘builtin_function_or_method’ object is not subscriptable“
  • “TypeError: ‘function’ object is not subscriptable“

Let’s look at an example of retrieving the first element of a list using the square bracket syntax

pizzas = ["margherita", "pepperoni", "four cheeses", "ham and pineapple"]
print(pizzas[0])

The code returns:

margherita

which is the pizza at index position 0. Let’s look at an example of calling a method using square brackets.

Example: Calling A Method With Square Brackets

Let’s create a program that stores fundamental particles as objects. The Particle class will tell us the mass of a particle and its charge. Let’s create a class for particles.

class Particle:

         def __init__(self, name, mass):

             self.name = name

             self.mass = mass

         def is_mass(self, compare_mass):

             if compare_mass != self.mass:

                 print(f'The {self.name} mass is not equal to {compare_mass} MeV, it is {self.mass} MeV')

             else:

                 print(f'The {self.name} mass is equal to {compare_mass} MeV')

The Particle class has two methods, one to define the structure of the Particle object and another to check if the mass of the particle is equal to a particular value. This class could be useful for someone studying Physics and particle masses for calculations.

Let’s create a muon object with the Particle class. The mass is in MeV and to one decimal place.

muon = Particle("muon", 105.7)

The muon variable is an object with the name muon and mass value 105.7. Let’s see what happens when we call the is_mass() method with square brackets and input a mass value.

muon.is_mass[105.7]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [18], in <cell line: 1>()
----> 1 muon.is_mass[105.7]

TypeError: 'method' object is not subscriptable

We raise the TypeError because of the square brackets used to call the is_mass() method. The square brackets are only suitable for accessing items from a list, a subscriptable object. Methods are not subscriptable; we cannot use square brackets when calling this method.

Solution

We replace the square brackets with the round brackets ().

muon = Particle("muon", 105.7)

Let’s call the is_mass method with the correct brackets.

muon.is_mass(105.7)

muon.is_mass(0.51)
The muon mass is equal to 105.7 MeV

The muon mass is not equal to 0.51 MeV, it is 105.7 MeV

The code tells us the mass is equal to 105.7 MeV but is not equal to the mass of the electron 0.51 MeV.

To learn more about correct class object instantiation and calling methods in Python go to the article titled “How to Solve Python missing 1 required positional argument: ‘self’“.

Summary

Congratulations on reading to the end of this tutorial! The error “TypeError: ‘method’ object is not subscriptable” occurs when you use square brackets to call a method. Methods are not subscriptable objects and therefore cannot be accessed like a list with square brackets. To solve this error, replace the square brackets with the round brackets after the method’s name when you are calling it.

To learn more about Python for data science and machine learning, go to the online courses page on Python for the best courses available!

Have fun and happy researching!

Welcome to another module of TypeError in the python programming language. In today’s article, we will be discussing an embarrassing Typeerror that usually gets landed up while we are a beginner to python. The error is named as TypeError: ‘method’ object is not subscriptable Solution.

In this guide, we’ll go through the causes and ultimately the solutions for this TypeError problem.

What are Subscriptable Objects in Python?

Subscriptable objects are the objects in which you can use the [item] method using square brackets. For example, to index a list, you can use the list[1] way.

Inside the class, the __getitem__ method is used to overload the object to make them compatible for accessing elements. Currently, this method is already implemented in lists, dictionaries, and tuples. Most importantly, every time this method returns the respective elements from the list.

Now, the problem arises when objects with the __getitem__ method are not overloaded and you try to subscript the object. In such cases, the ‘method’ object is not subscriptable error arises.

Why do you get TypeError: ‘method’ object is not subscriptable Error in python?

In Python, some of the objects can be used to access the inside elements by using square brackets. For example in List, Tuple, and dictionaries. But what happens when you use square brackets to objects which arent supported? It’ll throw an error.

Let us consider the following code snippet:

names = ["Python", "Pool", "Latracal", "Google"]
print(names[0])

int("5")[0]
OUTPUT:- Python
TypeError: int object is not subscriptable

This code returns “Python,” the name at the index position 0. We cannot use square brackets to call a function or a method because functions and methods are not subscriptable objects.

Example Code for the TypeError

x = 3
x[0] # example 1

p = True
p[0] # example 2

max[2] # example 3

OUTPUT:-

[Solved] TypeError: ‘method’ Object is not ubscriptable

Explanation of the code

  1. Here we started by declaring a value x which stores an integer value 3.
  2. Then we used [0] to subscript the value. But as integer doesn’t support it, an error is raised.
  3. The same goes for example 2 where p is a boolean.
  4. In example 3, max is a default inbuilt function which is not subscriptable.

The solution to the TypeError: method Object is not Subscriptable

The only solution for this problem is to avoid using square brackets on unsupported objects. Following example can demonstrate it –

x = 3
print(x)

p = True
print(p)

max([1])

OUTPUT:-

Our code works since we haven’t subscripted unsupported objects.

If you want to access the elements like string, you much convert the objects into a string first. The following example can help you to understand –

x = 3
str(x)[0] # example 1

p = True
str(p)[0] # example 2

Also, Read

FAQs

1. When do we get TypeError: ‘builtin_function_or_method’ object is not subscriptable?

Ans:- Let us look as the following code snippet first to understand this.

import numpy as np
a = np.array[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

OUTPUT:-

builtin_function_or_method' object is not subscriptable?

This problem is usually caused by missing the round parentheses in the np.array line.

It should have been written as:

a = np.array([1,2,3,4,5,6,7,8,9,10])

It is quite similar to TypeError: ‘method’ object is not subscriptable the only difference is that here we are using a library numpy so we get TypeError: ‘builtin_function_or_method’ object is not subscriptable.

Conclusion

The “TypeError: ‘method’ object is not subscriptable” error is raised when you use square brackets to call a method inside a class. To solve this error, make sure that you only call methods of a class using round brackets after the name of the method you want to call.

Now you’re ready to solve this common Python error like a professional coder! Till then keep pythoning Geeks!

One error that you might encounter when working with Python is:

TypeError: 'method' object is not subscriptable

This error occurs when you mistakenly call a class method using the square [] brackets instead of round () brackets.

The error is similar to the [‘builtin_function_or_method’ object is not subscriptable]({{ <ref “06-python-builtinfunctionormethod-object-is-not-subscriptable”>}}) in nature, except the error source is from a method you defined instead of built-in Python methods.

Let’s see an example that causes this error and how to fix it.

How to reproduce this error

Suppose you wrote a Python class in your code with a method defined in that class:

class Human:
    def talk(self, message):
        print(message)

Next, you create an instance of that class and call the talk() method, but instead of using parentheses, you used square brackets as shown below:

class Human:
    def talk(self, message):
        print(message)

person = Human()

person.talk["How are you?"]

The square brackets around talk["How are you?"] will cause an error:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    person.talk["How are you?"]
TypeError: 'method' object is not subscriptable

This is because Python thinks you’re trying to access an item from the talk variable instead of calling it as a method.

To resolve this error, you need to put parentheses around the string argument as follows:

person = Human()

person.talk("How are you?")  # ✅

By replacing the square brackets with parentheses, the function can be called and the error is resolved.

Sometimes, you get this error when you pass a list to a function without adding the parentheses.

Suppose the Human class has another method named greet_friends() which accepts a list of strings as follows:

class Human:
    def greet_friends(self, friends_list):
        for name in friends_list:
            print(f"Hi, {name}!")

Next, you create an instance of Human and call the greet_friends() method:

person = Human()

person.greet_friends['Lisa', 'John', 'Amy']  # ❌

Oops! The greet_friends method lacked parentheses, so you get the same error:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    person.greet_friends['Lisa', 'John', 'Amy']
TypeError: 'method' object is not subscriptable

Even when you’re passing a list to a method, you need to surround the list using parentheses as follows:

person.greet_friends( ['Lisa', 'John', 'Amy'] )  # ✅

By adding the parentheses, the error is now resolved and the person is able to greet those friends:

Hi, Lisa!
Hi, John!
Hi, Amy!

Conclusion

The TypeError: ‘method’ object is not subscriptable occurs when you call a class method using the square brackets instead of parentheses.

To resolve this error, you need to add parentheses after the method name. This rule applies even when you pass a list to the method as shown in the examples.

I hope this tutorial is helpful. See you in other tutorials! 👍

TypeError: builtin_function_or_method object is not subscriptable Python Error [SOLVED]

As the name suggests, the error TypeError: builtin_function_or_method object is not subscriptable is a “typeerror” that occurs when you try to call a built-in function the wrong way.

When a «typeerror» occurs, the program is telling you that you’re mixing up types. That means, for example, you might be concatenating a string with an integer.

In this article, I will show you why the TypeError: builtin_function_or_method object is not subscriptable occurs and how you can fix it.

Every built-in function of Python such as print(), append(), sorted(), max(), and others must be called with parenthesis or round brackets (()).

If you try to use square brackets, Python won’t treat it as a function call. Instead, Python will think you’re trying to access something from a list or string and then throw the error.

For example, the code below throws the error because I was trying to print the value of the variable with square braces in front of the print() function:

And if you surround what you want to print with square brackets even if the item is iterable, you still get the error:

gadgets = ["Mouse", "Monitor", "Laptop"]
print[gadgets[0]]

# Output: Traceback (most recent call last):
#   File "built_in_obj_not_subable.py", line 2, in <module>
#     print[gadgets[0]]
# TypeError: 'builtin_function_or_method' object is not subscriptable

This issue is not particular to the print() function. If you try to call any other built-in function with square brackets, you also get the error.

In the example below, I tried to call max() with square brackets and I got the error:

numbers = [5, 7, 24, 6, 90]
max_num = max(numbers)
print[max_num]

# Traceback (most recent call last):
#   File "built_in_obj_not_subable.py", line 11, in <module>
#     print[max_num]
# TypeError: 'builtin_function_or_method' object is not subscriptable

How to Fix the TypeError: builtin_function_or_method object is not subscriptable Error

To fix this error, all you need to do is make sure you use parenthesis to call the function.

You only have to use square brackets if you want to access an item from iterable data such as string, list, or tuple:

gadgets = ["Mouse", "Monitor", "Laptop"]
print(gadgets[0])

# Output: Mouse
numbers = [5, 7, 24, 6, 90]
max_num = max(numbers)
print(max_num)

# Output: 90

Wrapping Up

This article showed you why the TypeError: builtin_function_or_method object is not subscriptable occurs and how to fix it.

Remember that you only need to use square brackets ([]) to access an item from iterable data and you shouldn’t use it to call a function.

If you’re getting this error, you should look in your code for any point at which you are calling a built-in function with square brackets and replace it with parenthesis.

Thanks for reading.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Metatrader 4 общая ошибка
  • Metamask ошибка при получении котировок
  • Metamask обнаружил ошибку
  • Metal gear solid v the phantom pain ошибки
  • Metal gear rising revengeance ошибка при запуске