本文整理汇总了Python中numbers.Integral方法的典型用法代码示例。如果您正苦于以下问题:Python numbers.Integral方法的具体用法?Python numbers.Integral怎么用?Python numbers.Integral使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numbers
的用法示例。
在下文中一共展示了numbers.Integral方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_sensitivity
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def set_sensitivity(self, sensitivity):
"""Sets the sensitivity of the mechanism.
Parameters
----------
sensitivity : int
The sensitivity of the mechanism. Must satisfy `sensitivity` > 0.
Returns
-------
self : class
"""
if not isinstance(sensitivity, Integral):
raise TypeError("Sensitivity must be an integer")
if sensitivity < 0:
raise ValueError("Sensitivity must be non-negative")
self._sensitivity = sensitivity
self._scale = None
return self
示例2: set_bounds
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def set_bounds(self, lower, upper):
"""Sets the lower and upper bounds of the mechanism.
For the truncated geometric mechanism, `lower` and `upper` must be integer-valued. Must have
`lower` <= `upper`.
Parameters
----------
lower : int
The lower bound of the mechanism.
upper : int
The upper bound of the mechanism.
Returns
-------
self : class
"""
if not isinstance(lower, Integral) or not isinstance(upper, Integral):
raise TypeError("Bounds must be integers")
return super().set_bounds(lower, upper)
示例3: from_float
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def from_float(cls, f):
"""Converts a finite float to a rational number, exactly.
Beware that Fraction.from_float(0.3) != Fraction(3, 10).
"""
if isinstance(f, numbers.Integral):
return cls(f)
elif not isinstance(f, float):
raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
(cls.__name__, f, type(f).__name__))
if math.isnan(f):
raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
if math.isinf(f):
raise OverflowError("Cannot convert %r to %s." % (f, cls.__name__))
return cls(*f.as_integer_ratio())
示例4: from_decimal
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def from_decimal(cls, dec):
"""Converts a finite Decimal instance to a rational number, exactly."""
from decimal import Decimal
if isinstance(dec, numbers.Integral):
dec = Decimal(int(dec))
elif not isinstance(dec, Decimal):
raise TypeError(
"%s.from_decimal() only takes Decimals, not %r (%s)" %
(cls.__name__, dec, type(dec).__name__))
if dec.is_infinite():
raise OverflowError(
"Cannot convert %s to %s." % (dec, cls.__name__))
if dec.is_nan():
raise ValueError("Cannot convert %s to %s." % (dec, cls.__name__))
sign, digits, exp = dec.as_tuple()
digits = int(''.join(map(str, digits)))
if sign:
digits = -digits
if exp >= 0:
return cls(digits * 10 ** exp)
else:
return cls(digits, 10 ** -exp)
示例5: isint
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def isint(obj):
"""
Deprecated. Tests whether an object is a Py3 ``int`` or either a Py2 ``int`` or
``long``.
Instead of using this function, you can use:
>>> from future.builtins import int
>>> isinstance(obj, int)
The following idiom is equivalent:
>>> from numbers import Integral
>>> isinstance(obj, Integral)
"""
return isinstance(obj, numbers.Integral)
示例6: no
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def no(mytype, argnums=(1,)):
"""
A shortcut for the disallow_types decorator that disallows only one type
(in any position in argnums).
Example use:
>>> class newstr(object):
... @no('bytes')
... def __add__(self, other):
... pass
>>> newstr(u'1234') + b'1234' #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError: argument can't be bytes
The object can also be passed directly, but passing the string helps
to prevent circular import problems.
"""
if isinstance(argnums, Integral):
argnums = (argnums,)
disallowed_types = [mytype] * len(argnums)
return disallow_types(argnums, disallowed_types)
示例7: to_native
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def to_native(self, value, context=None):
if isinstance(value, bool):
value = int(value)
if isinstance(value, self.native_type):
return value
try:
native_value = self.native_type(value)
except (TypeError, ValueError):
pass
else:
if self.native_type is float: # Float conversion is strict enough.
return native_value
if not self.strict and native_value == value: # Match numeric types.
return native_value
if isinstance(value, (string_type, numbers.Integral)):
return native_value
raise ConversionError(self.messages['number_coerce']
.format(value, self.number_type.lower()))
示例8: _convert_header_value
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def _convert_header_value(self, value):
if isinstance(value, bytes):
pass
elif isinstance(value, unicode_type):
value = value.encode('utf-8')
elif isinstance(value, numbers.Integral):
# return immediately since we know the converted value will be safe
return str(value)
elif isinstance(value, datetime.datetime):
return httputil.format_timestamp(value)
else:
raise TypeError("Unsupported header value %r" % value)
# If \n is allowed into the header, it is possible to inject
# additional headers or split the request.
if RequestHandler._INVALID_HEADER_CHAR_RE.search(value):
raise ValueError("Unsafe header value %r", value)
return value
示例9: parse
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def parse(self, value):
_parse = {
datetime.datetime: self._parse_datetime,
datetime.timedelta: self._parse_timedelta,
bool: self._parse_bool,
basestring_type: self._parse_string,
}.get(self.type, self.type)
if self.multiple:
self._value = []
for part in value.split(","):
if issubclass(self.type, numbers.Integral):
# allow ranges of the form X:Y (inclusive at both ends)
lo, _, hi = part.partition(":")
lo = _parse(lo)
hi = _parse(hi) if hi else lo
self._value.extend(range(lo, hi + 1))
else:
self._value.append(_parse(part))
else:
self._value = _parse(value)
if self.callback is not None:
self.callback(self._value)
return self.value()
示例10: _decimalize
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def _decimalize(v, q = None):
# If already a decimal, just return itself
if type(v) == Decimal:
return v
# If tuple/list passed, bulk-convert
elif isinstance(v, (tuple, list)):
return type(v)(decimalize(x, q) for x in v)
# Convert int-like
elif isinstance(v, numbers.Integral):
return Decimal(int(v))
# Convert float-like
elif isinstance(v, numbers.Real):
if q != None:
return Decimal(repr(v)).quantize(Decimal(repr(q)),
rounding=ROUND_HALF_UP)
else:
return Decimal(repr(v))
else:
raise ValueError("Cannot convert {0} to Decimal.".format(v))
示例11: __setitem__
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def __setitem__(self, key, value):
if isinstance(key, numbers.Integral):
self.data[key] = value
else:
if not isinstance(value, (type(self),
compat.Sequence)):
# broadcast value
value = itertools.cycle([value])
if isinstance(key, np.ndarray) and key.dtype == 'bool':
# masking
for i, (k, v) in enumerate(zip(key, value)):
if k:
assert isinstance(v, self.dtype.type)
self.data[i] = v
else:
for k, v in zip(key, value):
assert isinstance(v, self.dtype.type)
self.data[k] = v
示例12: __init__
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def __init__(self, dimension=None, grids=None, data=None, gridnames=None,
dataname=None, name=None):
"""Create a GriddedField object.
Parameters:
dimension (int): Dimension of the GriddedField.
grids (list, tuple, np.ndarray): grids.
data (np.ndarray): data values.
gridnames (List[str]): clear names for all grids.
dataname (str): name of the data array.
name (str): name of the GriddedField.
"""
if not isinstance(dimension, numbers.Integral) or dimension < 1:
raise ValueError('dimension must be a scalar greater 0')
self._dimension = dimension
self.grids = copy.deepcopy(grids)
self.data = copy.copy(data)
self.gridnames = copy.copy(gridnames)
self.dataname = dataname
self.name = name
示例13: scale
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def scale(self, key, factor, dtype=float):
"""Scale data stored in field with given fieldname.
Notes:
This method only works, if the first grid
is an :arts:`ArrayOfString`.
Parameters:
key (str): Name of the field to scale.
factor (float or ndarray): Scale factor.
dtype (type): Data type used for typecasting. If the original
dtype of ``GriddedField.data`` is ``int``, the data array
gets typecasted to prevent messy behaviour when assigning
scaled values.
"""
if issubclass(self.data.dtype.type, numbers.Integral):
# Typecast integer data arrays to prevent unwanted typecast when
# assigning scaled (float) variables back to the (integer) ndarray.
self.data = self.data.astype(dtype)
self.set(key, self.get(key) * factor)
示例14: add
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def add(self, key, offset, dtype=float):
"""Add offset to data stored in field with given fieldname.
Notes:
This method only works, if the first grid
is an :arts:`ArrayOfString`.
Parameters:
key (str): Name of the field to offset.
offset (float or ndarray): Offset.
dtype (type): Data type used for typecasting. If the original
dtype of ``GriddedField.data`` is ``int``, the data array
gets typecasted to prevent messy behaviour when assigning
scaled values.
"""
if issubclass(self.data.dtype.type, numbers.Integral):
# Typecast integer data arrays to prevent unwanted typecast when
# assigning scaled (float) variables back to the (integer) ndarray.
self.data = self.data.astype(dtype)
self.set(key, self.get(key) + offset)
示例15: stringFromNumber
# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Integral [as 别名]
def stringFromNumber(self, number, decimals=None):
# Uses the current system locale, irrespective of language choice.
# Unless `decimals` is specified, the number will be formatted with 5 decimal
# places if the input is a float, or none if the input is an int.
if decimals == 0 and not isinstance(number, numbers.Integral):
number = int(round(number))
if platform == 'darwin':
if not decimals and isinstance(number, numbers.Integral):
return self.int_formatter.stringFromNumber_(number)
else:
self.float_formatter.setMinimumFractionDigits_(decimals or 5)
self.float_formatter.setMaximumFractionDigits_(decimals or 5)
return self.float_formatter.stringFromNumber_(number)
else:
if not decimals and isinstance(number, numbers.Integral):
return locale.format('%d', number, True)
else:
return locale.format('%.*f', (decimals or 5, number), True)