In addition to needing to inherit from object, properties only work on instances.
a = A()
a.db.doSomething("blah")
To make a property work on the class, you can define a metaclass. (A class is an instance of a metaclass, so properties defined on the metaclass work on the class, just as properties defined on a class work on an instance of that class.)
Answer from kindall on Stack OverflowIn addition to needing to inherit from object, properties only work on instances.
a = A()
a.db.doSomething("blah")
To make a property work on the class, you can define a metaclass. (A class is an instance of a metaclass, so properties defined on the metaclass work on the class, just as properties defined on a class work on an instance of that class.)
You aren't using classes correctly. A class is (normally) two things:
- A factory for creating a family of related objects
- A definition of the common behaviour of those objects
These related objects are the instances of the class. Normal methods are invoked on instances of the class, not on the class itself. If you want methods that can be invoked from the class, without an instance, you need to label the methods with @classmethod (or @staticmethod).
However I don't actually know whether properties work when retrieved from a class object. I can't check right now, but I don't think so. The error you are getting is that A.db is retrieving the property object which defines the property itself, it isn't "evaluating" the property to get A.__db. Property objects have no doSomething attribute. Properties are designed to be created in classes as descriptions of how the instances of those classes work.
If you did intend to be working with an instance of A, then you'll need to create one:
my_a = A()
my_a.db.doSomething("blah")
However, this will also fail. You have not correctly written getDB as any kind of method. Normal methods need an argument to represent the instance it was invoked on (traditionally called self):
def getDB(self):
...
Static methods don't, but need a decorator to label them as static:
@staticmethod
def getDB():
...
Class methods need both an argument to receive the class they were invoked on, and a decorator:
@classmethod
def getDB(cls):
...
Solved: AttributeError: 'property' object has no attribute 'add’ - MyActivateHandler - Autodesk Community
page.overlay.append - AttributeError: 'property' object has no attribute 'append'
Regression in pytest 8.3.1: AttributeError: 'property' object has no attribute '__code__' on Python 3.11 when combining doctest with property decoration
python - "AttributeError: 'property' object has no attribute 'get'" when using Depends in FastAPI - Stack Overflow
Videos
I'm sure that many people have encountered the following (code for reproduction below) behavior: if during the execution of `@property`, an `AttributeError` is raised and the same class implements `__getattr__` then `__getattr__` is invoked with the name of the property resulting in a confusing message: `AttributeError: 'Foo' object has no attribute 'something'`. If we remove `__getattr__` then we get a more meaningful and correct message: `AttributeError: 'Foo' object has no attribute 'bar'`.
from dataclasses import dataclass
@dataclass
class Foo: val = 'foo_value'
class Test:
def __init__(self):
self.foo = Foo()
def __getattr__(self, name):
return getattr(self.foo, name)
@property
def something(self):
return self.foo.bar
t = Test() t.somethingThe error message is misleading and the behavior catches many people (myself including) in surprise and results in many wasted hours of debugging. I've seen people recommend using a custom decorator (instead of `@property` that catches attribute error) or wrapping your `@property` bodies in `try/except`. But it seems to me that this should be dealt with on language level.
I'm trying to understand a few things:
Is this behavior in Python intentional (i.e. is there a good reason) or just stems from the fact that `__getattr__` is invoked when `AttributeError` is raised when an instance attribute is accessed?
If not intentional, is there a relatively easy way to detect `AttributeErrors` cause by `@property` execution in CPython? If so, why hasn't this been handled on language level?
I've searched CPython issues on Github and I saw someone trying to correct documentation but couldn't find issues asking about this behavior or suggestions to fix - am I missing something?
I've built a webscraper in python (Jupyter) to pull post content from a blog and I would like to use the csv file to create a wordcloud. This is the wordcloud code I am using:
%matplotlib notebook
from os import path
import matplotlib.pyplot as plt
import random
from wordcloud import WordCloud, STOPWORDS
# Open and read blog_stuff csv file
file = open("blog_stuff.csv",'r')
text = file.read()
file.close()
# Generate WordCloud
# !!!make sure the path for the font is correct!!!
wordcloud = WordCloud(font_path='C:/Windows/Fonts/Calibri.ttf', relative_scaling = 0.25 ).generate(text)
# Save image
plt.savefig('wordcloud.png')
# Display Image
plt.show()I keep running into an attribute error on all of the tutorials I follow. This is the error:
AttributeError Traceback (most recent call last) <ipython-input-34-20ba22870573> in <module> ----> 1 get_ipython().run_line_magic('matplotlib', 'notebook') 2 from os import path 3 import matplotlib.pyplot as plt 4 import random 5
~\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth) 2305 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals 2306 with self.builtin_trap: -> 2307 result = fn(*args, **kwargs) 2308 return result 2309
<C:\Users\MyName\Anaconda3\lib\site-packages\decorator.py:decorator-gen-109> in matplotlib(self, line)
~\Anaconda3\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k) 185 # but it's overkill for just that one bit of state. 186 def magic_deco(arg): --> 187 call = lambda f, *a, **k: f(*a, **k) 188 189 if callable(arg):
~\Anaconda3\lib\site-packages\IPython\core\magics\pylab.py in matplotlib(self, line) 97 print("Available matplotlib backends: %s" % backends_list) 98 else: ---> 99 gui, backend = self.shell.enable_matplotlib(args.gui) 100 self._show_matplotlib_backend(args.gui, backend) 101
~\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py in enable_matplotlib(self, gui) 3382 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) 3383 -> 3384 pt.activate_matplotlib(backend) 3385 pt.configure_inline_support(self, backend) 3386
~\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in activate_matplotlib(backend) 311 matplotlib.rcParams['backend'] = backend 312 --> 313 import matplotlib.pyplot 314 matplotlib.pyplot.switch_backend(backend) 315
~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in <module> 30 from cycler import cycler 31 import matplotlib ---> 32 import matplotlib.colorbar 33 import matplotlib.image 34 from matplotlib import rcsetup, style
~\Anaconda3\lib\site-packages\matplotlib\colorbar.py in <module> 25 26 import matplotlib as mpl ---> 27 import matplotlib.artist as martist 28 import matplotlib.cbook as cbook 29 import matplotlib.collections as collections
~\Anaconda3\lib\site-packages\matplotlib\artist.py in <module> 55 56 ---> 57 class Artist(object): 58 """ 59 Abstract base class for objects that render into a FigureCanvas.
~\Anaconda3\lib\site-packages\matplotlib\artist.py in Artist() 62 """ 63 @cbook.deprecated("3.1") ---> 64 @property 65 def aname(self): 66 return 'Artist'
~\Anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py in deprecate(obj, message, name, alternative, pending, addendum) 180 pass 181 """ --> 182 183 def deprecate(obj, message=message, name=name, alternative=alternative, 184 pending=pending, obj_type=obj_type, addendum=addendum):
AttributeError: 'property' object has no attribute 'name'
Would any of you fine folks know how I can remedy this issue?
Edit: Removed my name from path
Please Add A Flair To Your Post!
Suggested Flair: [Python]
To add a flair:
-
Click
flairunderneath your post -
Select a flair
-
Click
save
I am a bot run by /u/SupremeDesigner for r/CodingHelp || This was an automated ^response
Hi, how did you install matplotlib? Was it a conda installation? And which version of Matplotlib are you running on? Try upgrading it to the latest 3.2.1 version and run the program :)