Why property not accessible in Python? - python

GenericWidget is needed for rendering low-level elements, such as squares or text. They have a predefined size. Rendering is described in the render function. The Widget class has a build method, which should return the widgets that make up the widget that we make. The context (parent widget) must be passed to the build method. The problem is that when you try to get the widget size, there is a problem that the size parameter does not exist.
Here my example code:
class Widget:
def __init__(self, context):
self.__context__ = context
self.__update_instance__()
def build(self, context):
return NotImplemented
def render(self, xy):
self.__update_instance__()
self.__instance__.render(xy=xy)
def __update_instance__(self):
self.__instance__ = self.build(context=self.__context__)
self.size = self.__instance__.size
class GenericWidget(Widget):
def __init__(self, size):
self.size = size
super(GenericWidget, self).__init__(self)
def build(self, context):
return self
class GenericTest(GenericWidget):
def __init__(self):
super(GenericTest, self).__init__(size=(10, 10))
def render(self, xy):
# all rendering core here
pass
class Test2(Widget):
def build(self, context):
print(context.size)
return GenericTest()
class Test(Widget):
def build(self, context):
return Test2(self)
class OwnWidget(Widget):
def build(self, context):
return Test(self)
class Spacer(GenericWidget):
def __init__(self, size):
super(Spacer, self).__init__(size=size)
OwnWidget(Spacer((100, 100))).render(xy=(0, 0))
Traceback:
Traceback (most recent call last):
File "test.py", line 57, in <module>
OwnWidget(Spacer((100, 100))).render(xy=(0, 0))
File test.py", line 4, in __init__
self.__update_instance__()
File "test.py", line 14, in __update_instance__
self.__instance__ = self.build(context=self.__context__)
File "test.py", line 49, in build
return Test(self)
File "test.py", line 4, in __init__
self.__update_instance__()
File "test.py", line 14, in __update_instance__
self.__instance__ = self.build(context=self.__context__)
File "test.py", line 44, in build
return Test2(self)
File "test.py", line 4, in __init__
self.__update_instance__()
File "test.py", line 14, in __update_instance__
self.__instance__ = self.build(context=self.__context__)
File "test.py", line 38, in build
print(context.size)
AttributeError: 'Test' object has no attribute 'size'
Why size property are not accessible?

Related

Function is not accessed

this is my code:
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")
on hovering on on_enter_pressed function, it's showing function is not accessed and I'm getting the following error:
Traceback (most recent call last):
File "GUI.py", line 91, in <module>
app = ChatApplication()
File "GUI.py", line 15, in __init__
self._setup_main_window()
File "GUI.py", line 76, in _setup_main_window
self.msg_entry.bind("<Return>", self._on_enter_pressed)
AttributeError: 'ChatApplication' object has no attribute '_on_enter_pressed'
(I'm using tkinter in python to implement GUI.)
How can I solve this?
You have wrong indentations - _on_enter_pressed has to be outside __init__
def __init__(self):
# ... code ..
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
# outside `__init__`
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")

BloomFilter is at capacity after 10 minutes

I'm using Scrapy with a BloomFilter and after 10 minutes I have this error on loop :
2016-10-03 18:03:34 [twisted] CRITICAL:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/task.py", line 517, in _oneWorkUnit
result = next(self._iterator)
File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/defer.py", line 63, in <genexpr>
work = (callable(elem, *args, **named) for elem in iterable)
File "/usr/local/lib/python2.7/dist-packages/scrapy/core/scraper.py", line 183, in _process_spidermw_output
self.crawler.engine.crawl(request=output, spider=spider)
File "/usr/local/lib/python2.7/dist-packages/scrapy/core/engine.py", line 209, in crawl
self.schedule(request, spider)
File "/usr/local/lib/python2.7/dist-packages/scrapy/core/engine.py", line 215, in schedule
if not self.slot.scheduler.enqueue_request(request):
File "/usr/local/lib/python2.7/dist-packages/scrapy/core/scheduler.py", line 54, in enqueue_request
if not request.dont_filter and self.df.request_seen(request):
File "dirbot/custom_filters.py", line 20, in request_seen
self.fingerprints.add(fp)
File "/usr/local/lib/python2.7/dist-packages/pybloom/pybloom.py", line 182, in add
raise IndexError("BloomFilter is at capacity")
IndexError: BloomFilter is at capacity
The filter.py :
from pybloom import BloomFilter
from scrapy.utils.job import job_dir
from scrapy.dupefilters import BaseDupeFilter
class BLOOMDupeFilter(BaseDupeFilter):
"""Request Fingerprint duplicates filter"""
def __init__(self, path=None):
self.file = None
self.fingerprints = BloomFilter(2000000, 0.00001)
#classmethod
def from_settings(cls, settings):
return cls(job_dir(settings))
def request_seen(self, request):
fp = request.url
if fp in self.fingerprints:
return True
self.fingerprints.add(fp)
def close(self, reason):
self.fingerprints = None
I search on Google every possibilities but nothing work.
Thank's for your help.
Use pybloom.ScalableBloomFilter instead of BloomFilter.
from pybloom import ScalableBloomFilter
from scrapy.utils.job import job_dir
from scrapy.dupefilters import BaseDupeFilter
class BLOOMDupeFilter(BaseDupeFilter):
"""Request Fingerprint duplicates filter"""
def __init__(self,
path=None,
initial_capacity=2000000,
error_rate=0.00001,
mode=ScalableBloomFilter.SMALL_SET_GROWTH):
self.file = None
self.fingerprints = ScalableBloomFilter(
initial_capacity, error_rate, mode)

Devstack: TypeError: __init__() takes exactly 2 arguments (1 given)

I am getting this error when run horizon in devstack in eclipse. may be it's configuration error but I cannot solve it. please help
WARNING:root:No local_settings file found.
Traceback (most recent call last):
File "/home/stack/git/horizon/manage.py", line 23, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/Django-1.8-py2.7.egg/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/Django-1.8-py2.7.egg/django/core/management/__init__.py", line 303, in execute
settings.INSTALLED_APPS
File "/usr/local/lib/python2.7/dist-packages/Django-1.8-py2.7.egg/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/usr/local/lib/python2.7/dist-packages/Django-1.8-py2.7.egg/django/conf/__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python2.7/dist-packages/Django-1.8-py2.7.egg/django/conf/__init__.py", line 92, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/stack/git/horizon/openstack_dashboard/settings.py", line 339, in <module>
from horizon.utils import secret_key
File "/home/stack/git/horizon/horizon/__init__.py", line 27, in <module>
from horizon.base import Dashboard # noqa
File "/home/stack/git/horizon/horizon/base.py", line 45, in <module>
from horizon import loaders
File "/home/stack/git/horizon/horizon/loaders.py", line 57, in <module>
_loader = TemplateLoader()
File "/usr/local/lib/python2.7/dist-packages/Django-1.8-py2.7.egg/django/template/loader.py", line 50, in __init__
super(BaseLoader, self).__init__(*args, **kwargs)
TypeError: __init__() takes exactly 2 arguments (1 given)
Django loader file is showing error when run horizon. it showed type error in argument
import warnings
from django.utils.deprecation import RemovedInDjango20Warning
from .base import Origin
from .engine import Engine
class LoaderOrigin(Origin):
def __init__(self, display_name, loader, name, dirs):
super(LoaderOrigin, self).__init__(display_name)
self.loader, self.loadname, self.dirs = loader, name, dirs
def reload(self):
return self.loader(self.loadname, self.dirs)[0]
def find_template(*args, **kwargs):
return Engine.get_default().find_template(*args, **kwargs)
def get_template(*args, **kwargs):
return Engine.get_default().get_template(*args, **kwargs)
def get_template_from_string(*args, **kwargs):
return Engine.get_default().get_template_from_string(*args, **kwargs)
def render_to_string(*args, **kwargs):
return Engine.get_default().render_to_string(*args, **kwargs)
def select_template(*args, **kwargs):
return Engine.get_default().select_template(*args, **kwargs)
# This line must remain at the bottom to avoid import loops.
from .loaders import base
class BaseLoader(base.Loader):
_accepts_engine_in_init = False
def __init__(self, *args, **kwargs):
warnings.warn(
"django.template.loader.BaseLoader was superseded by "
"django.template.loaders.base.Loader.",
RemovedInDjango20Warning, stacklevel=2)
super(BaseLoader, self).__init__(*args, **kwargs)
Horizon requires Django>=1.4.2,<1.7, you're using Django 1.8 here (see requirements.txt)
The __init__ arguments for BaseLoader have changed between those two versions.
You need to fix your environment and dependencies if you want this to work.
May be there is no. of criteria for that type of problem ,
but in my case i am not initialize all the parameters in __init__() method
so this create a problem
def __init__(self, value, *args, **kwargs):
self.value = value
super(Custom_Vali, self).__init__(*args, **kwargs)
....
....
Run
test_c = Custom_Vali.get_error(89)
OR
test_c = Custom_Vali.get_error(value = 89)
O/P: TypeError: __init__() takes at least 2 arguments (1 given)
SOLUTION:
just set value=None or value = 0 in __init__
def __init__(self, value=0, *args, **kwargs):
self.value = value
super(Custom_Vali, self).__init__(*args, **kwargs)

Python class and function

I defined a function in my class, but when i called this function into my main program:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
And my main program is:
from dev import *
A=real()
C=A.func1(x)
Unfortunately i got this error:
Traceback (most recent call last):
File "PBC.py", line 4, in <module>
C=A.func1(0.2)
AttributeError: real instance has no attribute 'func1'
When i don't include the function in my class, my parameters are not recognized and i got this error:
Traceback (most recent call last):
File "PBC.py", line 75, in <module>
R_0=scipy.optimize.fsolve(func1,float(eps_real),args=(eps))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 127, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 183, in _root_hybr
_check_func('fsolve', 'func', func, x0, args, n, (n,))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 14, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
File "/home/cfd1/ndiaye/ATACAMAC/BCT_dev.py", line 75, in func1
self.k_ch=self.nmodes*self.pi/self.L_ch+eps/self.L_ch
AttributeError: 'numpy.ndarray' object has no attribute 'nmodes'
What can i do to avoid all this? Thank you for your answers.
Your above code runs if you just fix the indentation:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
A=real()
C=A.func1(5)
You have an indentation error. The lines starting def func1 should be lined up with def __init__.

error in a python class with an not iterable object

i have a the following error message
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2721, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-257-84ae6ec7b6f6>", line 1, in <module>
accuracy.ra_os
File "<ipython-input-255-a91d95432efe>", line 32, in ra_os
return np.average([(ref.intersection(s).area/s.area) for s in seg])
TypeError: 'Polygon' object is not iterable
where Polygon is the Polygon class of shapely.
i have my own class Accuracy: stat values between reference (one) and segmented (one or more) polygons
ref = <shapely.geometry.polygon.Polygon at 0x4997b38>
seg = [<shapely.geometry.polygon.Polygon at 0x4b972e8>, <shapely.geometry.polygon.Polygon at 0x49c7390>]
import math
import numpy as np
from shapely.geometry import Polygon
nan = np.nan
class Accuracy(object):
def __init__(self, ref, seg=None):
self.ref = ref
self.seg = seg
#property
def area(self):
return self.ref.area
#property
def perimeter(self):
return self.ref.length
#property
def centroidX(self):
return self.ref.centroid.x
#property
def centroidY(self):
return self.ref.centroid.y
#property
def segments(self):
if self.seg:
return len(self.seg)
else:
return 0
#property
def ra_or(self):
if self.seg:
return np.average([(ref.intersection(s).area/ref.area) for s in seg])
else:
return nan
#property
def ra_os(self):
if self.seg:
return np.average([(ref.intersection(s).area/s.area) for s in seg])
else:
return nan
accuracy = Accuracy(ref, seg_overlap)
accuracy.ra_os
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2721, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-45-84ae6ec7b6f6>", line 1, in <module>
accuracy.ra_os
File "<ipython-input-7-1e04291926b0>", line 35, in ra_os
return np.average([(ref.intersection(s).area/s.area) for s in seg])
TypeError: 'Polygon' object is not iterable
if i run the function outside the class i have not this error
np.average([(ref.intersection(s).area/ref.area) for s in seg_overlap])
Out[47]: 0.48709794373000681
Did you mean to say self.seg instead of just seg:
return np.average([(ref.intersection(s).area/ref.area) for s in self.seg])
^^^^^
(in both functions)
I think you're accidentally referring to the global object with the same name.

Categories

Resources