我是红宝石的新手,我正在玩IRB.
我发现我可以使用".methods"方法列出对象的方法,而self.methods类似于我想要的东西(类似于Python的dir(builtins)?),但我怎样才能找到方法库/模块我通过include和require加载?
irb(main):036:0* self.methods
=> ["irb_pop_binding", "inspect", "taguri", "irb_chws", "clone", "irb_pushws", "public_methods", "taguri=", "irb_pwws",
"public", "display", "irb_require", "irb_exit", "instance_variable_defined?", "irb_cb", "equal?", "freeze", "irb_context
", "irb_pop_workspace", "irb_cwb", "irb_jobs", "irb_bindings", "methods", "irb_current_working_workspace", "respond_to?"
, "irb_popb", "irb_cws", "fg", "pushws", "conf", "dup", "cwws", "instance_variables", "source", "cb", "kill", "help", "_
_id__", "method", "eql?", "irb_pwb", "id", "bindings", "send", "singleton_methods", "popb", "irb_kill", "chws", "taint",
"irb_push_binding", "instance_variable_get", "frozen?", "irb_source", "pwws", "private", "instance_of?", "__send__", "i
rb_workspaces", "to_a", "irb_quit", "to_yaml_style", "irb_popws", "irb_change_workspace", "jobs", "type", "install_alias
_method", "irb_push_workspace", "require_gem", …Run Code Online (Sandbox Code Playgroud) 在模块a.py中
def task():
print "task called"
a = task
class A:
func = task # this show error unbound method
#func = task.__call__ # if i replace with this work
def __init__(self):
self.func_1 = task
def test_1(self):
self.func_1()
@classmethod
def test(cls):
cls.func()
a()
A().test_1()
A.test()
Run Code Online (Sandbox Code Playgroud)
输出:
task called
task called
Traceback (most recent call last):
File "a.py", line 26, in <module>
A.test()
File "a.py", line 21, in test
cls.func()
TypeError: unbound method task() must be called with A instance …Run Code Online (Sandbox Code Playgroud) python class class-variables class-instance-variables python-2.7
我有一个类,该类将应用程序所需的所有资源(主要是图像)加载到内存中。
然后,几个线程需要通过此类访问这些资源。我不希望每个实例都重新加载所有资源,所以我以为我使用了Singleton模式。我这样做是这样的:
class DataContainer(object):
_instance = None
_lock = threading.Lock()
_initialised = True
def __new__(cls, *args, **kwargs):
with cls._lock:
if not cls._instance:
cls._initialised = False
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self, map_name = None):
# instance has already been created
if self._initialised:
return
self._initialised = True
# load images
Run Code Online (Sandbox Code Playgroud)
只要我不使用多个线程,它就可以正常工作。但是对于多个线程,每个线程都有一个不同的实例。因此,使用4个线程,它们每个都创建一个新实例。我希望所有线程都使用此类的相同实例,因此资源仅一次加载到内存中。
我也尝试在定义类的同一模块中执行此操作,但在类定义之外:
def getDataContainer():
global dataContainer
return dataContainer
dataContainer = DataContainer()
Run Code Online (Sandbox Code Playgroud)
但是每个线程仍然有自己的实例。
我是python的新手,如果这是错误的方法,请让我知道,谢谢您的帮助
python singleton multithreading multiprocessing parallel-python
我使用Metaclass创建 Singleton 类,它在多线程中运行良好,并且只创建 MySingleton 类的一个实例,但在多处理中,它总是创建新实例
import multiprocessing
class SingletonType(type):
# meta class for making a class singleton
def __call__(cls, *args, **kwargs):
try:
return cls.__instance
except AttributeError:
cls.__instance = super(SingletonType, cls).__call__(*args, **kwargs)
return cls.__instance
class MySingleton(object):
# singleton class
__metaclass__ = SingletonType
def __init__(*args,**kwargs):
print "init called"
def task():
# create singleton class instance
a = MySingleton()
# create two process
pro_1 = multiprocessing.Process(target=task)
pro_2 = multiprocessing.Process(target=task)
# start process
pro_1.start()
pro_2.start()
Run Code Online (Sandbox Code Playgroud)
我的输出:
init called
init called …Run Code Online (Sandbox Code Playgroud) 我遇到了一个奇怪的情况,经过大量的试打后无法解决。我正在使用多线程(10)来读取url(100),并且在大多数情况下都能正常工作,但在某些情况下,它会卡在最后一个线程中。我等待它查看是否返回,并且花费了很多时间(1050秒),而其余9个线程在25秒内返回了。它表明我的代码有问题,但无法解决。有任何想法吗?
注意1:守护程序线程和非守护程序线程均会发生这种情况。
注2:URL和线程更改的数量。我尝试了10-100个不同的URL和5-50个不同的线程。
注意3:URL在大多数情况下完全不同。
import urllib2
import Queue
import threading
from goose import Goose
input_queue = Queue.Queue()
result_queue = Queue.Queue()
Run Code Online (Sandbox Code Playgroud)
线程工作者:
def worker(input_queue, result_queue):
queue_full = true
while queue_full:
try:
url = input_queue.get(False)
read a url using urllib2 and goose
process it
result_queue.put(updated value)
except Queue.Empty:
queue_full = False
Run Code Online (Sandbox Code Playgroud)
主要过程:
for url in urls:
input_queue.put(url)
thread_count = 5
for t in range(thread_count):
t = threading.Thread(target=worker, args= (input_queue, result_queue))
t.start()
for url in urls:
url = result_queue.get() # updates url
Run Code Online (Sandbox Code Playgroud)
该过程在最后一次result_queue.get()调用时被阻塞。 …
python python-multithreading python-2.7 python-multiprocessing
尝试使用OpenCV库与kivy和python-for-android 播放视频
这是我的尝试:
import os
import cv2
from kivy.app import App
from kivy.clock import Clock
from kivy.graphics.texture import Texture
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.image import Image
class KivyCamera(Image):
def __init__(self, capture=None, fps=0, **kwargs):
super(KivyCamera, self).__init__(**kwargs)
# self.capture = cv2.VideoCapture("/sdcard2/python-apk/2.mp4")
print "file path exist :" + str(os.path.exists("/sdcard2/python-apk/1.mkv"))
self.capture = cv2.VideoCapture("/sdcard2/python-apk/1.mkv")
Clock.schedule_interval(self.update, 1.0 / fps)
def update(self, dt):
ret, frame = self.capture.read()
print str(os.listdir('/sdcard2/'))
if ret:
# convert it to texture
buf1 = …Run Code Online (Sandbox Code Playgroud) class Test(object):
def __init__(self):
pass
def testmethod(self):
# instance method
self.task(10) # type-1 access class method
cls = self.__class__
cls.task(20) # type-2 access class method
@classmethod
def task(cls,val)
print(val)
Run Code Online (Sandbox Code Playgroud)
我有两种方法可以将类方法访问实例方法。
self.task(10)
Run Code Online (Sandbox Code Playgroud)
要么
cls = self.__class__
cls.task(20)
Run Code Online (Sandbox Code Playgroud)
我的问题是哪一个最好,为什么?
如果两种方法都不相同,那么我在哪种条件下使用哪种方法?
在下面的示例中,Test类有两个实例方法和一个classmethod
在set_cls_var_1方法中,我使用self设置类变量.
在set_cls_var_2方法中,我使用self调用类方法.
class Test():
#class variable
cls_var = 10
def __init__(self):
obj_var=20
def set_cls_var_1(self,val):
#second method to access class variable
print "first "
self.cls_var = val
def set_cls_var_2(self):
print "second"
self.task(200)
@classmethod
def task(cls,val):
cls.cls_var = val
t=Test()
#set class variable by first method
t.set_cls_var_1(100)
print Test.cls_var
#set class variable by second method
t.set_cls_var_2()
print Test.cls_var
Run Code Online (Sandbox Code Playgroud)
产量
first
10
second
200
Run Code Online (Sandbox Code Playgroud)
预期产出
first
100
second
200
Run Code Online (Sandbox Code Playgroud)
我的问题是:为什么只有classmethod可以自己调用,为什么不是类变量
python ×7
python-2.7 ×6
class ×2
class-method ×2
singleton ×2
android ×1
buildozer ×1
irb ×1
kivy ×1
metaclass ×1
python-3.x ×1
ruby ×1