本文整理汇总了Python中property函数的典型用法代码示例。如果您正苦于以下问题:Python property函数的具体用法?Python property怎么用?Python property使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了property函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: interface
def interface(cls, name, uselist=True):
mapper = class_mapper(cls)
table = mapper.local_table
mapper.add_property(attr_name,
relationship(GenericAssoc,
backref='_backref_%s' % table.name)
)
if uselist:
# list based property decorator
def get(self):
if getattr(self, attr_name) is None:
setattr(self, attr_name, GenericAssoc(table.name))
return getattr(self, attr_name).targets
setattr(cls, name, property(get))
else:
# scalar based property decorator
def get(self):
return getattr(self, attr_name).targets[0]
def set(self, value):
if getattr(self, attr_name) is None:
setattr(self, attr_name, GenericAssoc(table.name))
getattr(self, attr_name).targets = [value]
setattr(cls, name, property(get, set))
示例2: __init__
def __init__(cls, name, base, namespace):
# store the Property definitions on the class as a dictionary
# mapping the Property name to the Property instance
cls._properties = {}
# loop through the class namespace looking for Property instances
for key, value in namespace.items():
#print key,value
if isinstance(value, Property):
if value.name is None:
# name will be none unless set via kwd param
value.name = key
cls._properties[key] = value
# now that the property reference is stored away,
# initialize its vars to None, the default vale (TODO), or the fget
if value.default:
#TODO: Make this work for scalars too
fget = getattr(cls,value.default)
value = property(fget)
elif value.fget:
# wrapped fset and fdel in str() to make the default None work with getattr
fget = getattr(cls,value.fget)
fset = getattr(cls,str(value.fset),None)
fdel = getattr(cls,str(value.fdel),None)
value = property(fget,fset,fdel)
else:
value = None
setattr(cls,key,value)
示例3: unclosure
def unclosure(prop, library):
def library_getter(self, static):
name = '_Qt__%s_%s' % (prop, 'static' if static else 'dynamic')
if getattr(self, name) is None:
lib = self._Qt__find_lib(library,
self._Qt__cxx_toolkit,
static = static)
setattr(self, name, lib)
return getattr(self, name)
setattr(Qt, '%s_dynamic' % prop,
property(lambda self: library_getter(self, False)))
setattr(Qt, '%s_static' % prop,
property(lambda self: library_getter(self, True)))
def config_getter(self, static = None, link = True):
if static is None:
static = not self._Qt__prefer_shared
name = '_Qt__config_%s_%s' % \
(prop, 'static' if static else 'dynamic')
if getattr(self, name) is None:
lib = library_getter(self, static)
c = Config()
macro = prop.upper()
macro += static and '_STATIC' or '_DYN'
c.define('Qt_%s_LINK' % macro, 1)
c.add_system_include_path(
Qt._Qt__include_dir / Qt._Qt__libraries[prop])
setattr(self, name + '_header', Config(c))
c.library_add(lib)
setattr(self, name, Config(c))
return getattr(self, name + ('_header' if not link else ''))
setattr(Qt, 'config_%s' % prop, config_getter)
示例4: __getattr__
def __getattr__(self, attr):
# Using an anonymous class
direction = self.direction
return type("", (object, ), {
'direction': property(lambda self: direction),
'type': property(lambda self: attr),
})()
示例5: _create_property
def _create_property(field_name, docstring,
read_only=False, closed_only=False):
"""Helper for creating properties to read/write to files.
"""
def getter(self):
if closed_only and not self._closed:
raise AttributeError("can only get %r on a closed file" %
field_name)
return self._file.get(field_name, None)
def setter(self, value):
if self._closed:
raise AttributeError("cannot set %r on a closed file" %
field_name)
self._file[field_name] = value
if read_only:
docstring = docstring + "\n\nThis attribute is read-only."
elif not closed_only:
docstring = "%s\n\n%s" % (docstring, "This attribute can only be "
"set before :meth:`close` has been called.")
else:
docstring = "%s\n\n%s" % (docstring, "This attribute is read-only and "
"can only be read after :meth:`close` "
"has been called.")
if not read_only and not closed_only:
return property(getter, setter, doc=docstring)
return property(getter, doc=docstring)
示例6: get_property
def get_property(self):
"""Returns the property in which the relation will be referenced."""
def _ws_inner(method_self):
"""Inner function to return the property for the relation."""
_klass = self.to_class()
self.__plural_name = _klass.__class__.plural_name
self.__get_all_cmd = _klass.data_source.get_all_cmd
if self.plural_name is not None:
plural_name = self.plural_name
else:
plural_name = method_self.plural_name
if not self.ws_call:
_klass.data_source.get_all_cmd = self.ws_call
ret = _klass.one(getattr(method_self, self.attr_fk))
else:
_klass.__class__.plural_name = "/".join(
(plural_name, getattr(method_self, self.attr_fk)))
_klass.data_source.get_all_cmd = self.ws_call
ret = _klass.many()
_klass.__class__.plural_name = self.__plural_name
_klass.data_source.get_all_cmd = self.__get_all_cmd
return ret
def _inner(method_self):
"""Inner function to return the property for the relation."""
fk = getattr(method_self, self.attr_fk)
return self.to_class.one(fk)
if self.ws_call is not None:
ret = property(_ws_inner)
else:
ret = property(_inner)
return ret
示例7: empty_info
def empty_info():
"""
Returns an empty info object
"""
return type('Info', (), {'object_type': property(lambda s: 'BASE'),
'metadata_backend_config': property(lambda s: None),
'vrouter_id': property(lambda s: None)})()
示例8: enum_type
def enum_type(*args):
"""
Create an enumeration from string arguments
"""
# Test args
for arg in args:
if not isinstance(arg, basestring):
msg = "{} is not a string".format(arg)
raise TypeError(msg)
# Format strings
values = [arg.strip() for arg in args]
# Create MetaEnum
values_property = property(lambda cls: values)
MetaEnum = type("MetaEnum", (type,), {"values": values_property})
# __new__ method
def __new__(cls, value):
if value not in cls.values:
msg = "'{}' not in {}".format(value, cls.values)
raise AttributeError(msg)
return BaseEnum.__new__(cls, value)
# __repr__ method
def __repr__(self):
return u"Element '{}' of Enum({})".format(unicode(self), self.values)
# method dictionnary
method_dict = {"__new__": __new__,
"__repr__": __repr__,
"values": property(lambda self: self.__class__.values)}
# Create EnumType
return MetaEnum("EnumType", (BaseEnum,), method_dict)
示例9: __init__
def __init__(self, rw_ops, lregs, loc_pfx, stk_pfx, frm_pfx):
self.__nibbles = 0
self.__nr = 0
self.__read, self.__write = rw_ops[1]
self.__list = []
self.__dico = {}
for regs in lregs:
sz = regs[0]
nm = regs[1]
for n in nm:
r = Register(self.__nr, n, sz, rw_ops[0])
fget = lambda me, who = self.__nr: me.__read_reg(who)
fset = lambda me, v, who = self.__nr: me.__write_reg(who,v)
if n.find(loc_pfx) != -1:
setattr(self.__class__, "pc", property(fget, fset))
self.__dico.update({"pc":self.__nr})
elif n.find(stk_pfx) != -1:
setattr(self.__class__, "stack", property(fget, fset))
self.__dico.update({"stack":self.__nr})
elif n.find(frm_pfx) != -1:
setattr(self.__class__, "frame", property(fget, fset))
self.__dico.update({"frame":self.__nr})
setattr(self.__class__, n, property(fget, fset))
self.__dico.update({n:self.__nr})
self.__list.append(r)
self.__nibbles += sz*2
self.__nr += 1
示例10: __new__
def __new__(cls, nm, parents, attrs):
super_new = super(CamelCasedClass, cls).__new__
tmp_dct = dict()
for name, value in attrs.items():
if not name.startswith('__') and not name.endswith('__'):
tmp_dct[name] = value
attrs.update(tmp_dct)
# Create property for each key in `description_map` dict.
# Besides, if `descriptor_type` is data descriptor, a `getxxx` and
# a `setxxx` method also will be added to `cls`, if `descriptor_type`
# is non data descriptor, only a `getxxx` method added.
if 'descriptor_map' in attrs:
for attr in attrs['descriptor_map']:
# Definition of getter and setter method for properties.
def get_attr(attr, self):
return self.getproperty(attr)
def set_attr(attr, self, value):
self.setproperty(attr, value)
property_name = attr
getter = partial(get_attr, attr)
setter = partial(set_attr, attr)
# Add property to class.
if attrs['descriptor_type'] == 'data descriptor':
# data descriptor.
attrs[property_name] = property(getter, setter, None, attr)
else:
# non data descriptor.
attrs[property_name] = property(getter, None, None, attr)
return super_new(cls, nm, parents, attrs)
示例11: _bounded_property
def _bounded_property(base_name, allowed_units, default_units, doc=""):
def getter(self):
return pq.Quantity(*split_unit_str(
self._query("{}?".format(base_name)),
default_units
))
def min_getter(self):
return pq.Quantity(*split_unit_str(self._query("{}:MIN?".format(base_name))))
def max_getter(self):
return pq.Quantity(*split_unit_str(self._query("{}:MAX?".format(base_name))))
def setter(self, newval):
newval = assume_units(newval, default_units)
if newval > max_getter(self) or newval < min_getter(self):
raise ValueError("Value outside allowed bounds for this channel.")
if newval.units not in allowed_units:
newval = newval.rescale(default_units)
self._sendcmd("{}:{}".format(base_name, newval))
return property(getter, setter, doc=doc), property(min_getter), property(max_getter)
示例12: __new__
def __new__(cls, clsname, clsbases, clsdict):
members = clsdict.get("__tcl_members__", list())
command = clsdict.get("__tcl_command__", None)
for (n, m) in enumerate(members):
if not isinstance(m, TclMember):
raise RuntimeError("Element #%d of __tcl_members__ is not a " "TclMember" % (n + 1,))
def fget(self, cmd=command, m=m):
self._ix_get(m)
val = self._api.call("%s cget -%s" % (cmd, m.name))[0]
return m.type(val)
def fset(self, value, cmd=command, m=m):
val = self._api.call("%s config -%s %s" % (cmd, m.name, value))
self._ix_set(m)
attrname = m.attrname
if m.attrname is None:
attrname = translate_ix_member_name(m.name)
if m.doc is not None:
fget.__doc__ = m.doc
fget.__name__ = "_get_%s" % attrname
clsdict[fget.__name__] = fget
if not m.flags & FLAG_RDONLY:
fset.__name__ = "_set_%s" % attrname
clsdict[fset.__name__] = fset
p = property(fget=fget, fset=fset)
else:
p = property(fget=fget)
clsdict[attrname] = p
t = type.__new__(cls, clsname, clsbases, clsdict)
return t
示例13: register
def register():
for i in range(len(models)):
model = models[i]
if '_decl_class_registry' in model.__dict__:
continue
_as_declarative(model, model.__name__, model.__dict__)
#for auto-update timestamps
event.listen(model, 'before_insert', ModelExtension.before_insert_listener)
event.listen(model, 'before_update', ModelExtension.before_update_listener)
# for ref grandchildren
for j in range(i):
if not models[j] in model.__bases__:
continue
parent = models[j]
for grandparent in parent._many_to_models:
setattr(grandparent, model._readable_names,
(lambda parent, model: property(lambda self: getattr(self, parent._readable_names)
.filter_by(real_type = model._readable_name)))(parent, model))
for grandparent in parent._one_to_models:
setattr(grandparent, model._readable_name,
(lambda parent, model: property(lambda self: getattr(self, parent._readable_name)
if getattr(self, parent._readable_name).real_type == model._readable_name else None))(parent, model))
models[:] = []
示例14: loadRI
def loadRI(libName):
"""Load a RenderMan library and return a module-like handle to it.
libName is the name of a shared library that implements the RenderMan
interface. The name can either be an absolute file name or just the
name of the library (without suffix or "lib" prefix) in which case
the function tries to find the library file itself.
The return value is the library handle as returned by the ctypes
LoadLibrary() function. This handle has already been prepared so that
it can be used like a module that contains the RenderMan interface.
"""
# Try to figure out the location of the lib if the name is not an absolute path...
libName = rmanlibutil.resolveRManLib(libName)
# Load the library...
ri = cdll.LoadLibrary(libName)
_createRiTypes(ri)
_createRiTokens(ri)
_createRiConstants(ri)
_createRiFunctions(ri)
# Create an alias for every Ri function and RI_ constant that has the prefix removed...
for name in dir(ri):
if name.startswith("Ri"):
setattr(ri, name[2:], getattr(ri, name))
elif name.startswith("RI_"):
setattr(ri, name[3:], getattr(ri, name))
ri.__class__.RiLastError = property(_getLastError, _setLastError)
ri.__class__.LastError = property(_getLastError, _setLastError)
return ri
示例15: bool_attrib_property
def bool_attrib_property(name, delete=False, default=None, doc=None):
'''XML boolean attribute property helper'''
# pylint: disable=W0212,C0111
def propget(myself):
att = get_attrib(myself._xml, name)
if att is not None:
return boolstr(att)
else:
return default
propget.xml_property = 'attrib'
propget.xml_name = name
def propset(myself, value):
if not type(value) == bool:
raise ValueError('Value has to be of the type bool')
if default is not None and default == value:
del_attrib(myself._xml, name)
else:
myself._xml.text = 'yes' if value == True else 'no'
if delete:
def propdel(myself):
del_attrib(myself._xml, name)
prop = property(propget, propset, propdel, doc=doc)
else:
prop = property(propget, propset, doc=doc)
return prop