>>> class Foo:
... 'it is a example'
... print 'i am here'
...
i am here
>>> Foo.__name__
'Foo'
>>> Foo().__name__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute '__name__'
>>> Foo.__doc__
'it is a example'
>>> Foo().__doc__
'it is a example'
>>> Foo.__dict__
{'__module__': '__main__', '__doc__': 'it is a example'}
>>> Foo().__dict__
{}
>>> Foo.__module__
'__main__'
>>> Foo().__module__
'__main__'
>>> myname=Foo()
>>> myname.__name__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute `__name__`
What is the reason instances have no attribute __name__
?
maybe it is ok that the __name__
of instance-myname is myname
.
would you mind tell me more logical, not the unreasonable grammar rules?
boatcoder
17.4k18 gold badges112 silver badges178 bronze badges
asked Jan 25, 2013 at 3:24
3
You’re seeing an artifact of the implementation of classes and instances. The __name__
attribute isn’t stored in the class dictionary; therefore, it can’t be seen from a direct instance lookup.
Look at vars(Foo)
to see that only __module__
and __doc__
are in the class dictionary and are visible to the instance.
For the instance to access the name of a class, it has to work its way upward with Foo().__class__.__name__
. Also note that classes have other attributes such as __bases__
that aren’t in the class dictionary and likewise cannot be directly accessed from the instance.
answered Jan 25, 2013 at 3:37
Raymond HettingerRaymond Hettinger
215k63 gold badges379 silver badges481 bronze badges
1
When I try to load data a translation dataset using TranslationDataset
class I get this error. There is no attribute named name
in Dataset
class or TranslationDataset
.
I tried do as specified in one of the test cases. https://github.com/pytorch/text/blob/master/test/translation.py#L75
data_set = datasets.TranslationDataset.splits(root='../data/',train='training.10k', validation='newstest2012', test='newstest2015',exts=('.de', '.en'), fields=(DE, EN))
~/anaconda3/envs/opennmt/lib/python3.6/site-packages/torchtext/datasets/translation.py in splits(cls, exts, fields, root, train, validation, test, **kwargs)
57 Dataset.
58 """
---> 59 path = cls.download(root)
60
61 train_data = None if train is None else cls(
~/anaconda3/envs/opennmt/lib/python3.6/site-packages/torchtext/data/dataset.py in download(cls, root, check)
109 dataset_path (str): Path to extracted dataset.
110 """
--> 111 path = os.path.join(root, cls.name)
112 check = path if check is None else check
113 if not os.path.isdir(check):
AttributeError: type object 'TranslationDataset' has no attribute 'name'
Here a simplified version of my code, but I can’t reproduce the bug that happens in my main program:
#file 1
import dill
import sympy as sp
import numpy as np
def run_symbo_comp():
sp.var("Nx,Ny,Xix,Xiy,kPenN,uix,uiy,x1x,x1y,x2x,x2y" )
sp.var("Ksi0, kPenT, Mu, sigmaT_tr ")
Xi = sp.Matrix([Xix, Xiy])
ui = sp.Matrix([uix, uiy])
x1 = sp.Matrix([x1x, x1y])
x2 = sp.Matrix([x2x, x2y])
xix = Xix + uix
xiy = Xiy + uiy
xi = sp.Matrix([xix, xiy])
a1_bar = x2 - x1
l = ((x2 - x1).dot( (x2 - x1).T))**(0.5)
a1 = (x2 - x1)/l
N = sp.Matrix([Nx, Ny])
gN = (xi - x1).dot(N)
W_N = 0.5 * kPenN * gN**2
dW_N = sp.Matrix([W_N.diff(uix), W_N.diff(uiy)])
DdW_N = sp.Matrix([dW_N.jacobian(ui)])
dW_N = sp.Matrix(2,1, sp.flatten(dW_N[0:2]))
DdW_N = sp.Matrix(2,2, sp.flatten( DdW_N[0:2, 0:2]))
with open('normal_ctc_penalty.dill', 'wb') as f: # Python 3: open(..., 'wb')
dill.dump((dW_N, DdW_N), f)
Ksi = (xi - x1).dot(a1) * (1/l)
gT = (Ksi - Ksi0)*l
dgT = sp.Matrix([gT.diff(uix), gT.diff(uiy)])
dW_stick = kPenT * gT * dgT
DdW_stick = dW_stick.jacobian(ui)
FN = ((kPenN *gN)**2)**0.5
dW_slip = Mu * FN * sp.sign(sigmaT_tr) * dgT
DdW_slip = Mu * FN * sp.sign(sigmaT_tr) * dgT.jacobian(ui)
dW_stick = sp.Matrix(2,1, sp.flatten(dW_stick[0:2]))
DdW_stick = sp.Matrix(2,2, sp.flatten( DdW_stick[0:2, 0:2]))
dW_slip = sp.Matrix(2,1, sp.flatten(dW_slip[0:2]))
DdW_slip = sp.Matrix(2,2, sp.flatten( DdW_slip[0:2, 0:2]))
with open('tgt_ctct_symbo.dill', 'wb') as f: # Python 3: open(..., 'wb')
dill.dump((dW_stick , dW_slip , DdW_stick , DdW_slip), f)
#file 2
import dill
import sympy as sp
import numpy as np
import FooSymbo
class FooClass():
def __init__(self):
# call the subroutine that generate sympy expressions and dump them
self.set_lambdas()
def set_lambdas(self):
"""
generate lambda functions and store them as attribute
"""
FooSymbo.run_symbo_comp()
with open('normal_ctc_penalty.dill', 'rb') as f:
(dWN, DdWN) = dill.load(f)
Nx,Ny,Xix,Xiy,kPenN,uix,uiy,x1x,x1y,x2x,x2y = sp.var('Nx,Ny,Xix,Xiy,kPenN,uix,uiy,x1x,x1y,x2x,x2y' )
#lambdification of the sympy expressions
# sympyfy the expression that I imported as .txt
args = (Nx,Ny,Xix,Xiy,kPenN,uix,uiy,x1x,x1y,x2x,x2y)
self.dWN = sp.lambdify(sp.flatten(args), dWN, 'numpy')
self.DdWN = sp.lambdify(sp.flatten(args), DdWN, 'numpy')
if __name__ == '__main__':
Foo = FooClass()
# raise Error on purpose
raise ValueError('')
I will try again to trigger the error tomorrow
In my code I dump and load using an absolute path.
Can it be related ?
Anyway, this is a more complete description of the error that happened just now, in the case it helps:
`
AttributeError Traceback (most recent call last)
/Users/marco.magliulo/repos/COMMON_ROOT_MYPROG/Python/OOP_2DLattice/Scripts/TESTS/Test1_unconstrained.py in ()
136
137 if name == ‘main‘:
—> 138 result = main()
139 if result == 1:
140 print(‘Test1 : success n’)
/Users/marco.magliulo/repos/COMMON_ROOT_MYPROG/Python/OOP_2DLattice/Scripts/TESTS/Test1_unconstrained.py in main()
57
58 Latt = ElastoPlast2DLatt(Xmin, Ymin, nbrX, nbrY, dX, dY, E_arr, A_arr,
—> 59 diagTrusses,ElastoPlast, sigma_y0_arr, H_arr, Contact)
60
61 ################################################################################
/Users/marco.magliulo/repos/COMMON_ROOT_MYPROG/Python/OOP_2DLattice/Classes/ElastoPlast2D.py in init(self, Xmin, Ymin, nbrX, nbrY, dX, dY, E_arr, A_arr, diagTrusses, ElastoPlast, sigma_y0_arr, H_arr, Contact, TupleContactVar)
116 self.Friction = False
117 # generation lambda functions for Fint and Kint
—> 118 self.unconstrain_lambda()
119 # spot the nodes on the border of the lattice
120 self.onS = np.zeros((self.Nn), dtype=bool)
/Users/marco.magliulo/repos/COMMON_ROOT_MYPROG/Python/OOP_2DLattice/Classes/ElastoPlast2D.py in unconstrain_lambda(self)
400
401 with open(‘PDer_Energy_Unconstrained.pickle’, ‘rb’) as f: # Python 3: open(…, ‘rb’)
—> 402 (F, K) = dill.load(f)
403
404 uix, uiy, Xix, Xiy, ujx, ujy, Xjx, Xjy, E, A, eps_p = sp.symbols(‘uix, uiy, Xix, Xiy, ujx, ujy, Xjx, Xjy, E, A, eps_p’)
/Users/marco.magliulo/miniconda2/envs/EnvAvecPython3/lib/python3.5/site-packages/dill/dill.py in load(file)
249 pik._main = _main_module
250 obj = pik.load()
—> 251 if type(obj).module == _main_module.name: # point obj class to main
252 try: obj.class == getattr(pik._main, type(obj).name)
253 except AttributeError: pass # defined in a file
AttributeError: module has no attribute ‘name‘
`
This is another article regarding on the error message triggered. The error itself is triggered upon executing a page which is accessed from an URL of a web-based page powered by Django framework. This is happened because of the attribute named ‘home’ doesn’t exist. Below is the actual error message shown :
AttributeError: 'module' object has no attribute 'home'
Because of the error triggered above, the page is not loaded as shown in the following image :
As it can be shown in the above image, because of the error , the page cannot be loaded at all. It is unavoidable since it is considered an error which is failing the execution of the page. Certainly it cannot be accessed since the page which is being accessed is a home page. In the home page, the URL is being processed by the URL definition in the file named url.py. It is located in the folder of the main project. Below is the description of the location :
user@hostname:~/myproject/apps$ tree -L 3 . . ├── bin ... ├── include ... ├── lib ...├── local ... ├── src │ ├── db.sqlite3 │ ├── apps │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── settings.py │ │ ├── settings.pyc │ │ ├── urls.py │ │ ├── urls.pyc │ │ ├── wsgi.py │ │ └── wsgi.pyc │ ├── manage.py ... │ └── contact │ ├── admin.py │ ├── admin.pyc │ ├── apps.py │ ├── __init__.py │ ├── __init__.pyc │ ├── migrations │ ├── models.py │ ├── models.pyc │ ├── templates │ ├── tests.py │ ├── views.py │ └── views.pyc ... └── xxx 28 directories, 90 files user@hostname:~/myproject/apps$
Considered the project named is ‘myproject’ based on the above output. The application which is considered as a module in the above context is contact. So, based on the error generated which is presented in the previous section of this article, the module named ‘contact’ doesn’t have any attribute named ‘home’. It is obvious since the URL definition on the url file named urls.py located in the directory as shown in the tree command output generated named ‘contact’ exist. It is shown as follows :
from contact import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), ]
But the attribute as shown in the url defined, the attribute ‘home’ which is expected is there from the views.py imported from the module named ‘apps’ doesn’t exist. Below is the content of the views.py located in the folder named ‘contact’ :
from django.shortcuts import render # Create your views here.
To solve the problem, just add a new definition or attribute named ‘home’ inside the file named ‘views.py’ as shown below :
def home(request): context = locals() template = 'home.html' return render(request,template,context)
Try to load the home page again off course with the additional action by creating a folder named templates and also a file named ‘home.html’ inside of it.
Sep-25-2020, 03:23 PM
(This post was last modified: Sep-25-2020, 03:24 PM by deathsperance.)
Trying to grab an excel file from azure blob store and put into azure sql server instance. it was working and suddenly stopped. It was running on a coworkers machine and he is using 3.7 I am using 3.8.
Hoping someone can see something simple were missing.
Getting this error when I run it.
‘table_name’: tbl.name,
AttributeError: ‘str’ object has no attribute ‘name’
import io import requests import openpyxl import pandas as pd from sqlalchemy import create_engine import urllib #Target Server Connection String params = urllib.parse.quote_plus(r'Driver={ODBC Driver 17 for SQL Server};Server=servernamehere,1433;Uid=adminuser;Pwd=testpswd;database=Stage;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;') #Blob snapshot URL pulled from azure blob input_excel = requests.get('https://testdata.blob.core.uscloudapi.net/testing6data/testing.xlsx, stream=True) conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params) engn = create_engine(conn_str,echo=True) # Loads the excel file into the eb variable wb = openpyxl.load_workbook(filename=io.BytesIO(input_excel.content), data_only='True') tables_dict = {} # Go through each worksheet in the workbook for ws_name in wb.sheetnames: #print(wb.sheetnames) print("") print(f"worksheet name: {ws_name}") ws = wb[ws_name] print(f"tables in worksheet: {len(ws._tables)}") # Get each table in the worksheet for tbl in ws._tables: # First, add some info about the table to the dictionary tables_dict[tbl.name] = { 'table_name': tbl.name, 'worksheet': ws_name, 'num_cols': len(tbl.tableColumns), 'table_range': tbl.ref} # Grab the 'data' from the table data = ws[tbl.ref] # Now convert the table 'data' to a Pandas DataFrame # First get a list of all rows, including the first header row rows_list = [] for row in data: # Get a list of all columns in each row cols = [] for col in row: cols.append(col.value) rows_list.append(cols) # Create a pandas dataframe from the rows_list. # The first row is the column names df = pd.DataFrame(data=rows_list[1:], index=None, columns=rows_list[0]) # Add the dataframe to the dictionary of tables # df = df.dropna(how='any') df.to_sql(tbl.name, engn, if_exists='append',schema='testing') print(df) tables_dict[tbl.name]['dataframe'] = df print('-----------------------------done------------------------')
Posts: 11,607
Threads: 449
Joined: Sep 2016
Reputation:
444
Please show complete unmodified error traceback. (in error tags)
It contains valuable process information on what happened prior to error, and more.
Posts: 2
Threads: 1
Joined: Sep 2020
Reputation:
0
Sorry you can delete my post, it was just a simple version error with openpyxl
Posts: 1,815
Threads: 2
Joined: Apr 2017
Reputation:
85
Sep-25-2020, 04:25 PM
(This post was last modified: Sep-25-2020, 04:25 PM by ndc85430.)
When something stops working, it’s useful to work out what changed in that time, to help narrow down the cause. Did the code change at all? Something in the environment? Does it work on one version of Python and not the other?
Posts: 11,607
Threads: 449
Joined: Sep 2016
Reputation:
444
Sep-25-2020, 04:36 PM
(This post was last modified: Sep-25-2020, 04:37 PM by Larz60+.)
Thread/Post Deletion
By posting on the forums you agree to the terms of the registration agreement of permitting us to retain that content for our database. You agree that any content you post is under the default MIT license allowing rights to use, copy, modify, merge, publish, distribute, sublicense, and/orThread/Post Deletion
see for complete forum rule: https://python-forum.io/misc.php?action=help&hid=32
Я создаю дискорд бота и при выводе информации о разбане в embed, выдает ошибку Command raised an exception: AttributeError: ‘str’ object has no attribute ‘name’
@bot.command(pass_context = True)
@commands.has_permissions(view_audit_log=True)
async def unban(ctx,*,member):
await ctx.channel.purge(limit = 1)
emb = discord.Embed (title = 'Unban :unlock:', colour = 15105570)
banned_users = await ctx.guild.bans()
for ban_entry in banned_users:
user = ban_entry.user
await ctx.guild.unban (user)
emb = discord.Embed (title = 'Unban :lock:', colour = 15105570)
emb.set_author (name = member.name, icon_url = member.avatar_url)
emb.add_field (name = 'Ban user', value = 'Baned user : {}'.format(member.mention))
emb.set_footer (text = 'Был заблокирован администратором {}'.format (ctx.author.name), icon_url = ctx.author.avatar_url)
await ctx.send( embed = emb)
В консоли выдает это
Ignoring exception in command unban:
Traceback (most recent call last):
File "C:UsersalopaAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "E:Новая папка (2)main.py", line 74, in unban
emb.set_author (name = member.name, icon_url = member.avatar_url)
AttributeError: 'str' object has no attribute 'name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:UsersalopaAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandsbot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:UsersalopaAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:UsersalopaAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'name'
Прошу помогите!
Attributes are functions or properties associated with an object of a class. Everything in Python is an object, and all these objects have a class with some attributes. We can access such properties using the .
operator.
This tutorial will discuss the object has no attribute python
error in Python. This error belongs to the AttributeError
type.
We encounter this error when trying to access an object’s unavailable attribute. For example, the NumPy
arrays in Python have an attribute called size
that returns the size of the array. However, this is not present with lists, so if we use this attribute with a list, we will get this AttributeError
.
See the code below.
import numpy as np
arr1 = np.array([8,4,3])
lst = [8,4,3]
print(arr1.size)
print(lst.size)
Output:
3
AttributeError: 'list' object has no attribute 'size'
The code above returns the size
of the NumPy
array, but it doesn’t work with lists and returns the AttributeError
.
Here is another example with user-defined classes.
class A:
def show():
print("Class A attribute only")
class B:
def disp():
print("Class B attribute only")
a = A()
b = B()
b.show()
Output:
AttributeError: 'B' object has no attribute 'show'
In the example above, two classes were initiated with similar functions to display messages. The error shows because the function called is not associated with the B
class.
We can tackle this error in different ways. The dir()
function can be used to view all the associated attributes of an object. However, this method may miss attributes inherited via a metaclass.
We can also update our object to the type that supports the required attribute. However, this is not a good method and may lead to other unwanted errors.
We can also use the hasattr()
function. This function returns True if an attribute belongs to the given object. Otherwise, it will return False.
See the code below.
class A:
def show():
print("Class A attribute only")
class B:
def disp():
print("Class B attribute only")
a = A()
b = B()
lst = [5,6,3]
print(hasattr(b, 'disp'))
print(hasattr(lst, 'size'))
Output:
In the example above, object b
has the attribute disp
, so the hasattr()
function returns True. The list doesn’t have an attribute size
, so it returns False.
If we want an attribute to return a default value, we can use the setattr()
function. This function is used to create any missing attribute with the given value.
See this example.
class B:
def disp():
print("Class B attribute only")
b = B()
setattr(b, 'show', 58)
print(b.show)
Output:
The code above attaches an attribute called show
with the object b
with a value of 58
.
We can also have a code where we are unsure about the associated attributes in a try
and except
block to avoid any error.
One error that you might encounter when working with Python classes is:
AttributeError: 'X' object has no attribute 'Y'
This error usually occurs when you call a method or an attribute of an object. There are two possible reasons for this error:
- The method or attribute doesn’t exist in the class.
- The method or attribute isn’t a member of the class.
The following tutorial shows how to fix this error in both cases.
1. The method or attribute doesn’t exist in the class
Let’s say you code a class named Human
with the following definitions:
class Human:
def __init__(self, name):
self.name = name
def walk(self):
print("Walking")
Next, you created an object from this class and called the eat()
method:
person = Human("John")
person.eat()
You receive an error because the eat()
method is not defined in the class:
Traceback (most recent call last):
File "main.py", line 10, in <module>
person.eat()
AttributeError: 'Human' object has no attribute 'eat'
To fix this you need to define the eat()
method inside the class
as follows:
class Human:
def __init__(self, name):
self.name = name
def walk(self):
print("Walking")
def eat(self):
print("Eating")
person = Human("John")
person.eat() # Eating
Now Python can run the eat()
method and you won’t receive the error.
The same goes for attributes you want the class to have. Suppose you want to get the age
attribute from the person
object:
person = Human("John")
print(person.age) # ❌
The call to person.age
as shown above will cause an error because the Human
class doesn’t have the age
attribute.
You need to add the attribute into the class:
class Human:
age = 22
def __init__(self, name):
self.name = name
def walk(self):
print("Walking")
person = Human("John")
print(person.age) # 22
With the attribute defined inside the class, you resolved this error.
2. The method or attribute isn’t a member of the class
Suppose you have a class with the following indentations in Python:
class Human:
def __init__(self, name):
self.name = name
def walk():
print("Walking")
Next, you created a Human
object and call the walk()
method as follows:
person = Human("John")
person.walk() # ❌
You’ll receive an error as follows:
Traceback (most recent call last):
File "main.py", line 9, in <module>
person.walk()
AttributeError: 'Human' object has no attribute 'walk'
This error occurs because the walk()
method is defined outside of the Human
class block.
How do I know? Because you didn’t add any indent before defining the walk()
method.
In Python, indentations matter because they indicate a block of code, like curly brackets {}
in Java or JavaScript.
When you write a member of the class, you need to indent each line according to the class structure you want to create.
The indentations must be consistent, meaning if you use a space, each indent must be a space. The following example uses one space for indentations:
class Human:
def __init__(self, name):
self.name = name
def walk(self):
print("Walking")
This one uses two spaces for indentations:
class Human:
def __init__(self, name):
self.name = name
def walk(self):
print("Walking")
And this uses four spaces for indentations:
class Human:
def __init__(self, name):
self.name = name
def walk(self):
print("Walking")
When you incorrectly indent a function, as in not giving any indent to the walk()
method, then that method is defined outside of the class:
class Human:
def __init__(self, name):
self.name = name
def walk():
print("Walking")
# Valid
walk() # ✅
# Invalid
person = Human("John")
person.walk() # ❌
You need to appropriately indent the method to make it a member of the class. The same goes when you’re defining attributes for the class:
class Human:
age = 22
def __init__(self, name):
self.name = name
def walk(self):
print("Walking")
# Valid
person = Human("John")
person.walk() # ✅
print(person.age) # ✅
You need to pay careful attention to the indentations in your code to fix the error.
I hope this tutorial is helpful. Have fun coding! 😉
In this article, we will explain the solutions on how to resolve the ‘function’ object has no attribute and why this error occurs
Before we proceed to solve the error function object has no attribute, we will first need to know what ‘function’ object has no attribute?
The “Function object has no attribute” is an error message that usually occurs in Python if you are trying to access an attribute, which is like a method or property that doesn’t exist on a function object.
This means that you are trying to call a method or access a property on a function that won’t support that particular attribute.
This will happen if you misspell the attribute name or use the wrong name for the function.
For example:
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
# Create a Rectangle object
my_rectangle = Rectangle(4, 5)
# Try to access a non-existent attribute on the area method
my_rectangle.area.color
In this code example, we define a class called Rectangle that has an __init__ method to initialize its length and width attributes, and an area method that calculates the rectangle’s area.
Then, we create a Rectangle object with a length of 4 and a width of 5.
However, in the next line, we try to access a non-existent attribute color on the area method of the my_rectangle object.
This will result in an AttributeError: ‘function’ object has no attribute error because the area method which doesn’t have a color attribute defined.
If we run the code example above, the output will be like this:
C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
Traceback (most recent call last):
File “C:UsersDellPycharmProjectspythonProjectmain.py”, line 13, in
my_rectangle.area.color
AttributeError: ‘function’ object has no attribute ‘color’
Also, you may read the other python error resolution:
- attributeerror: module time has no attribute clock [SOLVED]
- Attributeerror: can’t set attribute [Solved]
- Attributeerror: ‘axessubplot’ object has no attribute ‘bar_label’
- Attributeerror: ‘list’ object has no attribute ‘encode’ [SOLVED]
Causes of the function object has no attribute
The main cause of the AttributeError: function object has no attribute error in Python is trying to access an attribute that does not exist on a function object.
Here are some possible reasons why this error might occur:
- Misspelling the attribute name
- Using the wrong name for the function
- Using a function as a variable
- Using a method or attribute that does not exist
How to solve the function’ object has no attribute?
Here are some solutions and examples on how to solve the “AttributeError: ‘function’ object has no attribute” error:
Solution 1: Check the spelling
It is possible that you might misspell the attribute or method that you are trying to access. Make sure that the spelling matches exactly with what you are using.
For example:
def my_function(): return "This is an example of function object has no attribute!" print(my_function.lenght) # incorrect spelling
Output:
C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
Traceback (most recent call last):
File “C:UsersDellPycharmProjectspythonProjectmain.py”, line 4, in
print(my_function.Length) # incorrect spelling
AttributeError: ‘function’ object has no attribute ‘lenght’
In this example, the spelling of “lenght” was wrong. Yet, the correct spelling must be “len”. So the corrected code it should be:
def my_function():
return "This is an example of function object has no attribute!"
print(len(my_function())) # correct spelling
Output:
C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
55
Solution 2: Check the object type
You will make sure that you are trying to access the attribute or method on the correct object type. For example:
number = 5
# error because integer doesn't have an upper() method
print(number.upper())
Output:
C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
Traceback (most recent call last):
File “C:UsersDellPycharmProjectspythonProjectmain.py”, line 3, in
print(number.upper())
AttributeError: ‘int’ object has no attribute ‘upper’
In the code example above, we are trying to call the “upper” method on an integer, which does not have that method. Instead, we should be using a string.
Let’s take a look at the correct example below:
word = "This is the correct example of object type"
print(word.upper()) # correct
Output:
C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
THIS IS THE CORRECT EXAMPLE OF OBJECT TYPE
Solution 3: Check the scope
You will make sure that the attribute or method should define in the correct scope.
For example:
def my_function():
name = "juan"
print(name.upper()) # error because name is not defined in this scope
Output:
C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
Traceback (most recent call last):
File “C:UsersDellPycharmProjectspythonProjectmain.py”, line 4, in
print(name.upper()) # error because name is not defined in this scope
AttributeError: ‘function’ object has no attribute ‘name’
In the code example above, we are trying to access the “name” variable outside of the function where it was defined. Instead, we should be returning the variable from the function and accessing it from there:
For example:
def my_function():
name = "Juan"
return name
print(my_function().upper()) # correct
Output:
C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
JUAN
Solution 4: Check the code flow
You can trace the code flow and make sure that the function you are calling is actually being executed and returning the expected object.
For example:
def my_function():
return "welcome to itsourcecode.com"
print(my_function.upper()) # error because we forgot to call my_function
Output:
C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
Traceback (most recent call last):
File “C:UsersDellPycharmProjectspythonProjectmain.py”, line 4, in
print(my_function.upper()) # error because we forgot to call my_function
AttributeError: ‘function’ object has no attribute ‘upper’
In the code example above, we forget to call the “my_function” before we are trying to access the “upper” method. Instead, we should be calling the function:
def my_function(): return "welcome to itsourcecode.com" print(my_function().upper()) # correct
Output:
C:UsersDellPycharmProjectspythonProjectvenvScriptspython.exe C:UsersDellPycharmProjectspythonProjectmain.py
WELCOME TO ITSOURCECODE.COM
FAQs
What is the “AttributeError: ‘function’ object has no attribute” error?
The “AttributeError: ‘function’ object has no attribute” error occurs when you try to access an attribute or method of an object that doesn’t exist.
This will happen if you mistype the attribute name, or if the attribute isn’t defined in the object’s class or in any of its parent classes.
Conclusion
To conclude, you should be able to solve the attributeerror: ‘function’ object has no attribute through the following solutions in this article.