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! 👍

Arguments in Python methods must be specified within parentheses. This is because functions and methods both use parentheses to tell if they are being called. If you use square brackets to call a method, you’ll encounter an “TypeError: ‘method’ object is not subscriptable” error.

In this guide, we discuss what this error means and why you may encounter it. We walk through an example of this error to help you develop a solution.

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.

TypeError: ‘method’ object is not subscriptable

Subscriptable objects are objects with a __getitem__ method. These are data types such as lists, dictionaries, and tuples. The __getitem__ method allows the Python interpreter to retrieve an individual item from a collection.

Not all objects are subscriptable. Methods, for instance, are not. This is because they do not implement the __getitem__ method. This means you cannot use square bracket syntax to access the items in a method or to call a method.

Consider the following code snippet:

cheeses = ["Edam", "Stilton", "English Cheddar", "Parmesan"]
print(cheeses[0])

This code returns “Edam”, the cheese 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.

An Example Scenario

Here, we build a program that stores cheeses in objects. The “Cheese” class that we use to define a cheese will have a method that lets us check whether a cheese is from a particular country of origin.

Start by defining a class for our cheeses. We call this class Cheese:

class Cheese:
	def __init__(self, name, origin):
		self.name = name
		self.origin = origin

	def get_country(self, to_compare):
		if to_compare == self.origin:
			print("{} is from {}.".format(self.name, self.origin))
		else:
			print("{} is not from {}. It is from {}.".format(self.name, to_compare, self.origin))

Our class contains two methods. The first method defines the structure of the Cheese object. The second lets us check whether the country of origin of a cheese is equal to a particular value. 

Next, we create an object from our Cheese class:

edam = Cheese("Edam", "Netherlands")

The variable “edam” is an object. The name associated with the cheese is Edam and its country of origin is the Netherlands.

Next, let’s call our get_country() method:

edam.get_country["Germany"]

This code executes the get_country() method from the Cheese class. The get_country() method checks whether the value of “origin” in our “edam” object is equal to “Germany”.

Run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 14, in <module>
	edam.get_country["Germany"]
TypeError: 'method' object is not subscriptable

An error occurs in our code.

The Solution

Let’s analyze the line of code that the Python debugger has identified as erroneous:

edam.get_country["Germany"]

In this line of code, we use square brackets to call the get_country() method. This is not acceptable syntax because square brackets are used to access items from a list. Because functions and objects are not subscriptable, we cannot use square brackets to call them.

To solve this error, we must replace the square brackets with curly brackets:

edam.get_country("Germany")

Let’s run our code and see what happens:

Edam is not from Germany. It is from Netherlands.

Our code successfully executes. Let’s try to check whether Edam is from “Netherlands” to make sure our function works in all cases, whether or not the value we specify is equal to the cheese’s origin country:

edam.get_country("Netherlands")

Our code returns:

Edam is from Netherlands.

Our code works if the value we specify is equal to the country of origin of a cheese.

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 curly 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!

  • Metal gear solid v the phantom pain ошибка при запуске 3dmgame dll
  • Metal gear solid v the phantom pain ошибка при запуске 0xc0000906
  • Metal gear solid v the phantom pain ошибка steam
  • Metal gear solid v the phantom pain ошибка msvcp110 dll
  • Metal gear solid v the phantom pain ошибка mgsvtpp exe