本文整理汇总了Python中new.instancemethod函数的典型用法代码示例。如果您正苦于以下问题:Python instancemethod函数的具体用法?Python instancemethod怎么用?Python instancemethod使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了instancemethod函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: enable_router_hints
def enable_router_hints():
import new
from django.db import DEFAULT_DB_ALIAS, router
from landlord.conf import settings
def _router_func(action):
def _route_db(self, model, **hints):
from landlord import landlord
hints.update({settings.LANDLORD_DEFAULT_NAMESPACE_KEY: landlord.get_current_namespace()})
chosen_db = None
for router in self.routers:
try:
method = getattr(router, action)
except AttributeError:
# If the router doesn't have a method, skip to the next one.
pass
else:
chosen_db = method(model, **hints)
if chosen_db:
return chosen_db
try:
return hints["instance"]._state.db or DEFAULT_DB_ALIAS
except KeyError:
return DEFAULT_DB_ALIAS
return _route_db
router.db_for_read = new.instancemethod(_router_func("db_for_read"), router, None)
router.db_for_write = new.instancemethod(_router_func("db_for_write"), router, None)
示例2: add_filters
def add_filters():
"""Add filters for every choice in ItemToPush.STATUS.
This filters are mostly useless except if you do a lot of management from
command line"""
constants = [c for c in dir(models.ITEM_TO_PUSH_STATUS) if c.isupper() and c not in NOT_CONSTANTS]
for current_constant in constants:
method_name = current_constant.lower()
def get_filter_function(constant):
def filter_by_status(self):
value = getattr(models.ITEM_TO_PUSH_STATUS, constant)
return self.filter(status=value)
return filter_by_status
filter_by_status = get_filter_function(current_constant)
filter_by_status_method = instancemethod(filter_by_status, None, BaseQuerySet)
setattr(BaseQuerySet, method_name, filter_by_status_method)
def get_query_function(name):
def query_by_status(self):
method = getattr(self.get_query_set(), name)
return method()
return query_by_status
query_by_status = get_query_function(method_name)
query_by_status_method = instancemethod(query_by_status, None, BaseManager)
setattr(BaseManager, method_name, query_by_status_method)
示例3: test_0020_static_file_url
def test_0020_static_file_url(self):
with Transaction().start(DB_NAME, USER, CONTEXT):
self.setup_defaults()
file_buffer = buffer('test-content')
file = self.create_static_file(file_buffer)
self.assertFalse(file.url)
app = self.get_app()
static_file_obj = self.static_file_obj
with app.test_client() as c:
# Patch the home page method
def home_func(self, file_id):
return render_template(
'home.jinja',
static_file_obj=static_file_obj,
static_file_id=file_id,
)
home_func = functools.partial(home_func, file_id=file.id)
c.application.view_functions[
'nereid.website.home'] = new.instancemethod(
home_func, self.nereid_website_obj
)
self.nereid_website_obj.home = new.instancemethod(
home_func, self.nereid_website_obj
)
rv = c.get('/en_US/')
self.assertTrue('/en_US/static-file/test/test.png' in rv.data)
self.assertEqual(rv.status_code, 200)
示例4: __init__
def __init__(self, category_algorithm, rank_by, frequency_bins = None):
if category_algorithm == "frequency-ifos-oninstruments":
self.category_func = lambda self, on_instruments, participating_instruments, frequency: (on_instruments, participating_instruments, self.frequency_bins[frequency])
elif category_algorithm == "oninstruments":
self.category_func = lambda self, on_instruments, participating_instruments, frequency: on_instruments
else:
raise ValueError, category_algorithm
self.category_func = instancemethod(self.category_func, self, self.__class__)
if rank_by == "snr":
self.reputation_func = lambda self, snr, uncombined_ifar, likelihood: snr
elif rank_by == "uncombined-ifar":
# cast to float so this does the right thing when
# we get "inf" as a string
self.reputation_func = lambda self, snr, uncombined_ifar, likelihood: float(uncombined_ifar)
elif rank_by == "likelihood":
self.reputation_func = lambda self, snr, uncombined_ifar, likelihood: likelihood
else:
raise ValueError, rank_by
self.rank_by = rank_by
self.reputation_func = instancemethod(self.reputation_func, self, self.__class__)
self.frequency_bins = frequency_bins
self.reputations = {}
self.cached_livetime = {}
self.extrapolate = False
self.extrapolation_coeffs = {}
self.categories = []
示例5: __init__
def __init__(cls, name, bases, cls_dict):
cls.use_metaclass = 1
def fake_method(self):
pass
new.instancemethod(fake_method, None, cls)
示例6: __init__
def __init__(self, link, flash_type):
self.stopped = False
self.status = ''
self.link = link
self.flash_type = flash_type
self._waiting_for_callback = False
self._read_callback_data = []
self.link.add_callback(ids.FLASH_DONE, self._done_callback)
self.link.add_callback(ids.FLASH_READ, self._read_callback)
self.ihx_elapsed_ops = 0 # N operations finished in self.write_ihx
self.ihx_total_ops = None # Total operations in self.write_ihx call
if self.flash_type == "STM":
self.flash_type_byte = 0
self.addr_sector_map = stm_addr_sector_map
# Add STM-specific functions.
self.__dict__['lock_sector'] = \
new.instancemethod(_stm_lock_sector, self, Flash)
self.__dict__['unlock_sector'] = \
new.instancemethod(_stm_unlock_sector, self, Flash)
self.n_sectors = STM_N_SECTORS
self.restricted_sectors = STM_RESTRICTED_SECTORS
elif self.flash_type == "M25":
self.flash_type_byte = 1
self.addr_sector_map = m25_addr_sector_map
# Add M25-specific functions.
self.__dict__['write_status'] = \
new.instancemethod(_m25_write_status, self, Flash)
self.n_sectors = M25_N_SECTORS
self.restricted_sectors = M25_RESTRICTED_SECTORS
else:
raise ValueError("flash_type must be \"STM\" or \"M25\"")
示例7: __init__
def __init__(self, api_token, endpoint="https://shreddr.captricity.com/api/backbone/schema", version=None):
"""
endpoint must be the full url to the API schema document, like `http://127.0.0.1:8000/api/backbone/schema'
api_token is the unique string associated with your account's profile which allows API access
"""
self.api_token = api_token
self.endpoint = endpoint
self.parsed_endpoint = urlparse.urlparse(self.endpoint)
self.api_version = version
schema_url = self.parsed_endpoint.path
if version: schema_url = schema_url + '?version=' + version
self.schema = self._get_data(schema_url)
self.api_version = self.schema['version']
for resource in self.schema['resources']:
if "GET" in resource['allowed_request_methods']:
read_callable = _generate_read_callable(resource['name'], resource['display_name'], resource['arguments'], resource['regex'], resource['doc'], resource['supported'])
setattr(self, read_callable.__name__, new.instancemethod(read_callable, self, self.__class__))
if "PUT" in resource['allowed_request_methods']:
update_callable = _generate_update_callable(resource['name'], resource['display_name'], resource['arguments'], resource['regex'], resource['doc'], resource['supported'], resource['put_syntaxes'])
setattr(self, update_callable.__name__, new.instancemethod(update_callable, self, self.__class__))
if "POST" in resource['allowed_request_methods']:
create_callable = _generate_create_callable(resource['name'], resource['display_name'], resource['arguments'], resource['regex'], resource['doc'], resource['supported'], resource['post_syntaxes'], resource['is_action'])
setattr(self, create_callable.__name__, new.instancemethod(create_callable, self, self.__class__))
if "DELETE" in resource['allowed_request_methods']:
delete_callable = _generate_delete_callable(resource['name'], resource['display_name'], resource['arguments'], resource['regex'], resource['doc'], resource['supported'])
setattr(self, delete_callable.__name__, new.instancemethod(delete_callable, self, self.__class__))
示例8: __init__
def __init__(self, link, flash_type, sbp_version, max_queued_ops=1):
"""
Object representing either of the two flashes (STM/M25) on the Piksi,
including methods to erase, program, and read.
Parameters
----------
link : sbp.client.handler.Handler
Handler to send messages to Piksi over and register callbacks with.
flash_type : string
Which Piksi flash to interact with ("M25" or "STM").
sbp_version : (int, int)
SBP protocol version, used to select messages to send.
max_queued_ops : int
Maximum number of Flash read/program operations to queue in device flash.
(0.5 * ADDRS_PER_OP + SBP packet overhead) * max_queued_ops is how much
of the device UART RX buffer will be filled by the program/read callback
messages. A higher value will significantly speed up flashing, but can
result in RX buffer overflows in other UARTs if the device is receiving
data on other UARTs.
Returns
-------
out : Flash instance
"""
self._n_queued_ops = 0
self.max_queued_ops = max_queued_ops
self.nqo_lock = Lock()
self.stopped = False
self.status = ''
self.link = link
self.flash_type = flash_type
self.sbp_version = sbp_version
# IntelHex object to store read flash data in that was read from device.
self._read_callback_ihx = IntelHex()
self.link.add_callback(self._done_callback, SBP_MSG_FLASH_DONE)
self.link.add_callback(self._read_callback, SBP_MSG_FLASH_READ_RESP)
self.ihx_elapsed_ops = 0 # N operations finished in self.write_ihx
if self.flash_type == "STM":
self.flash_type_byte = 0
self.addr_sector_map = stm_addr_sector_map
# Add STM-specific functions.
self.__dict__['lock_sector'] = \
new.instancemethod(_stm_lock_sector, self, Flash)
self.__dict__['unlock_sector'] = \
new.instancemethod(_stm_unlock_sector, self, Flash)
self.n_sectors = STM_N_SECTORS
self.restricted_sectors = STM_RESTRICTED_SECTORS
elif self.flash_type == "M25":
self.flash_type_byte = 1
self.addr_sector_map = m25_addr_sector_map
# Add M25-specific functions.
self.__dict__['write_status'] = \
new.instancemethod(_m25_write_status, self, Flash)
self.n_sectors = M25_N_SECTORS
self.restricted_sectors = M25_RESTRICTED_SECTORS
else:
raise ValueError(
"flash_type must be \"STM\" or \"M25\", got \"%s\"" %
flash_type)
示例9: test_template_rendered
def test_template_rendered(self):
with Transaction().start(DB_NAME, USER, CONTEXT):
self.setup_defaults()
app = self.get_app()
# Patch the home page method
def home_func(self):
return nereid.render_template(
'home.jinja', whiskey=42
)
app.view_functions['nereid.website.home'] = \
new.instancemethod(
home_func, self.nereid_website_obj
)
self.nereid_website_obj.home = new.instancemethod(
home_func, self.nereid_website_obj
)
recorded = []
def record(sender, template, context):
recorded.append((template, context))
flask.template_rendered.connect(record, app)
try:
app.test_client().get('/')
self.assertEqual(len(recorded), 1)
template, context = recorded[0]
self.assertEqual(template.name, 'home.jinja')
self.assertEqual(context['whiskey'], 42)
finally:
flask.template_rendered.disconnect(record, app)
示例10: __init__
def __init__(self, hardware_obj):
QObject.__init__(self)
self.setIn = new.instancemethod(lambda self: None, self)
self.setOut = self.setIn
self.getState = new.instancemethod(lambda self: "unknown", self)
self.dev = hardware_obj
try:
sClass = str(self.dev.__class__)
i, j = re.search("'.*'", sClass).span()
except BaseException:
dev_class = sClass
else:
dev_class = sClass[i + 1 : j - 1]
self.devClass = dev_class.split(".")[-1]
# print "Type is",self.devClass
if self.devClass == "Device":
self.devClass = "Procedure"
if not self.devClass in (
"WagoPneu",
"Shutter",
"SpecMotorWSpecPositions",
"Procedure",
):
self.devClass = "WagoPneu"
initFunc = getattr(self, "init%s" % self.devClass)
initFunc()
self.setIn = getattr(self, "setIn%s" % self.devClass)
self.setOut = getattr(self, "setOut%s" % self.devClass)
self.getState = getattr(self, "getState%s" % self.devClass)
示例11: test_request_exception_signal
def test_request_exception_signal(self):
with Transaction().start(DB_NAME, USER, CONTEXT):
self.setup_defaults()
app = self.get_app()
app.config['DEBUG'] = False
recorded = []
# Patch the home page method
def home_func(self):
1 // 0
app.view_functions['nereid.website.home'] = \
new.instancemethod(
home_func, self.nereid_website_obj
)
self.nereid_website_obj.home = new.instancemethod(
home_func, self.nereid_website_obj
)
def record(sender, exception):
recorded.append(exception)
flask.got_request_exception.connect(record, app)
try:
self.assertEqual(
app.test_client().get('/').status_code, 500
)
self.assertEqual(len(recorded), 1)
assert isinstance(recorded[0], ZeroDivisionError)
finally:
flask.got_request_exception.disconnect(record, app)
示例12: test_0020_static_file_url
def test_0020_static_file_url(self):
with Transaction().start(testing_proxy.db_name, 1, None) as txn:
file_id, = self.static_file_obj.search([], limit=1)
file = self.static_file_obj.browse(file_id)
self.assertFalse(file.url)
app = self.get_app()
with app.test_client() as c:
# Patch the home page method
def home_func(self, file_id):
static_file_obj = Pool().get('nereid.static.file')
return render_template(
'home.jinja',
static_file_obj=static_file_obj,
static_file_id=file_id,
)
home_func = functools.partial(home_func, file_id=file_id)
c.application.view_functions[
'nereid.website.home'] = new.instancemethod(
home_func, self.website_obj
)
self.website_obj.home = new.instancemethod(
home_func, self.website_obj
)
rv = c.get('/en_US/')
self.assertTrue('/en_US/static-file/test/test.png' in rv.data)
self.assertEqual(rv.status_code, 200)
示例13: override_replace
def override_replace(target, name, func, combiner=replacement, reverse=False):
obj = target
cls = target.__class__
is_derived = False
# The function is defined in the superclass (which we don't override)
if not name in cls.__dict__:
is_derived = True
# Bind the call to the superclass function
orig_func = new.instancemethod(lambda self, *args, **named: getattr(super(cls, self), name).__call__(*args,**named), obj, cls)
else:
orig_func = getattr(obj, name)
if not hasattr(orig_func, "stacked"):
stacked_func = stacked_function(orig_func, combiner=combiner, reverse=reverse)
setattr(target, name, stacked_func)
else: stacked_func = orig_func
# Add the replacement effect along with the card name (in case of multiple effects)
new_func = [new.instancemethod(func, obj, cls), name, False] #card.name, False]
stacked_func.add_func(new_func)
def restore(stacked_func=stacked_func):
stacked_func.remove_func(new_func)
if not stacked_func.stacking():
setattr(target, name, stacked_func.funcs[0])
del stacked_func
func.expire = restore
return restore
示例14: decorator
def decorator(orig):
if isinstance(orig, (new.classobj, type)):
cls2 = orig
class Before(object): pass
b = Before()
setattr(cls, "Before" + cls2.__name__, b)
setattr(cls2, "super", b)
for k, v in cls2.__dict__.items():
if isinstance(v, new.function):
f = decorator(v)
setattr(b, f.func_name, f.__original__)
v.__original__ = f.__original__
return cls2
else:
f = orig
func_name = f.func_name
replacement_method = new.instancemethod(f, None, cls)
def monkeypatch(*a, **k):
return replacement_method(*a, **k)
f = monkeypatch
f.func_name = func_name
method = getattr(cls, func_name, None)
f.__original__ = method
setattr(cls, func_name,
new.instancemethod(f, None, cls))
return f
示例15: __call__
def __call__( cls, *args, **kwargs ):
instance = cls.__new__( cls )
instance.__init__( *args, **kwargs )
setUpMethods = []
tearDownMethods = []
for _cls in reversed( cls.__mro__ ):
setUp = getattr( _cls, 'setUp', None )
tearDown = getattr( _cls, 'tearDown', None )
if setUp:
if not len( setUpMethods ) or setUp != setUpMethods[-1]:
setUpMethods.append( setUp )
if tearDown:
if not len( tearDownMethods ) or tearDown != tearDownMethods[0]:
tearDownMethods.insert( 0, tearDown )
def chain( methods ):
def fun( self ):
for method in methods:
method( self )
return fun
instance.setUp = new.instancemethod( chain( setUpMethods ), instance, cls )
instance.tearDown = new.instancemethod( chain( tearDownMethods ), instance, cls )
return instance