我正在尝试编写一个函数来打印常见STL容器(向量,列表等)的表示.我给函数一个模板参数T,例如,它可能代表向量.我在获取类型为T的迭代器时遇到问题
vector<int> v(10, 0);
repr< vector<int> >(v);
Run Code Online (Sandbox Code Playgroud)
...
template <typename T>
void repr(const T & v)
{
cout << "[";
if (!v.empty())
{
cout << ' ';
T::iterator i;
for (i = v.begin();
i != v.end()-1;
++i)
{
cout << *i << ", ";
}
cout << *(++i) << ' ';
}
cout << "]\n";
}
Run Code Online (Sandbox Code Playgroud)
...
brett@brett-laptop:~/Desktop/stl$ g++ -Wall main.cpp
main.cpp: In function ‘void repr(const T&)’:
main.cpp:13: error: expected ‘;’ before ‘i’
main.cpp:14: error: ‘i’ was not declared in …Run Code Online (Sandbox Code Playgroud) 默认情况下,当IPython显示一个对象时,它似乎正在使用__repr__.
__repr__在给定合适的环境的情况下,应该生成一个可用于重建对象的唯一字符串.这不同于__str__,它应该产生人类可读的输出.
现在假设我们已经编写了一个特定的类,我们希望IPython默认生成人类可读的输出(即没有显式调用print或__str__).我们不希望通过使我们的类的捏造它__repr__做__str__的工作.这将破坏规则.
有没有办法告诉IPython __str__默认为特定类调用?
在Matlab中,可以使用eval函数将任意字符串作为代码进行评估.例如
s = '{1, 2, ''hello''}' % char
c = eval(s) % cell
Run Code Online (Sandbox Code Playgroud)
有没有办法进行逆运算; 获取任意变量的文字字符串表示?那就是s从中恢复c?就像是
s = repr(c)
Run Code Online (Sandbox Code Playgroud)
这样的repr函数是内置在Python中的,但我在Matlab中没有遇到类似的东西,也没有看到自己如何实现它的明确方法.
我所知道的最接近的东西是disp(c)打印出一种表示形式c,但是以"可读"格式而不是文字代码格式.
repr(super(class, thing))不同super(class, thing).__repr__()?我遇到过一些我认为很奇怪的事情,如果有人解释为什么它的工作方式会很好,那就太棒了.
我的问题是如何repr运作
class MyInt(int):
pass
one = MyInt(1)
sup = super(MyInt, one)
Run Code Online (Sandbox Code Playgroud)
>>> repr(sup)
"<super: <class 'MyInt'>, <MyInt object>>"
而
>>> sup.__repr__()
'1'
第二个是我期望从第一个开始的(是的,引用在每种情况下都不同).为什么这些案件有所repr不同?我以为repr(x)刚刚打过电话x.__repr__.
据我所知,super为超类的方法提供了一个API,而不是超类本身.所以在我看来,我sup有两个__repr__方法,一个由名称调用repr,一个名称在名称之下__repr__.非常感谢能够深入了解这里发生的事情.
在巨蟒(3.5.2),我期待的repr(obj)函数调用魔术方法__repr__()的obj的课。然而,调用它们似乎不会产生相同的结果。谁能解释为什么?
示例代码:
class parent:
def __init__(self):
self.a = "haha"
def __repr__(self):
return repr(self.a)
class child(parent):
def __init__(self):
super().__init__()
self.b="bebe"
def __repr__(self):
return "("+super().__repr__()+", "+repr(super())+", "+self.b+")"
def print1(self):
print("super().__repr__() returns:", super().__repr__())
print("repr(super()) returns:", repr(super()))
print("plom(super()).__repr__() returns:", plom(super()).__repr__())
print("repr(plom(super())) returns:", repr(plom(super())))
def plom(var):
return var
t=child()
print(t.__repr__())
print(repr(t))
print('-----')
t.print1()
print('-----')
print(plom(t).__repr__())
print(repr(plom(t)))
Run Code Online (Sandbox Code Playgroud)
结果 :
>>>
RESTART: test super.py
('haha', <super: <class 'child'>, <child object>>, bebe)
('haha', <super: <class 'child'>, <child object>>, bebe)
-----
super().__repr__() returns: …Run Code Online (Sandbox Code Playgroud) 我在 SQLAlchemy 中有一堆要定义的表__repr__。
标准约定似乎是这样的:
def __repr__(self):
return "<TableName(id='%s')>" % self.id
Run Code Online (Sandbox Code Playgroud)
这对小桌子来说都很好。但是,我有 40 多列的表格。 有没有更好的构造方法,__repr__这样我就不用手动输入大量字符串?
我的包含所有表的文件称为models.py. 一种解决方案我想到了制作方法,_create_repr_string在models.py该负责自动生成的字符串进行__repr__返回。我想知道是否有更标准的方法来创建__repr__.
我有一个读取位并创建枚举的函数。目前,调用者需要提供 EnumType 和该枚举的表示形式。如何更改函数,以便从 EnumType 推导出表示形式,以便调用者只需要提供 EnumType 而不是其表示形式?
// Example enum:
use num_enum::TryFromPrimitive;
#[derive(Debug, Clone, Copy, TryFromPrimitive)]
#[repr(u8)]
pub enum VehicleType {
Boat = 0,
Car = 1,
}
// Example of current functional call
extract_enum_bits::<VehicleType, u8>(&data, 2, 6);
// Current function:
fn extract_enum_bits<EnumType: std::convert::TryFrom<Repr>, Repr: ReadInto>(data: &[u8],start_bit: u64, bits_to_read: u8) -> EnumType
where <EnumType as std::convert::TryFrom<Repr>>::Error : std::fmt::Debug {
let enum_as_repr_int = extract_bits::<Repr>(&data, start_bit, bits_to_read);
EnumType::try_from(enum_as_repr_int).unwrap()
}
Run Code Online (Sandbox Code Playgroud)
想要的函数调用语法:
extract_enum_bits::<VehicleType>(&data, 2, 6)
Run Code Online (Sandbox Code Playgroud)
如何更改函数 extract_enum_bits 以支持这种新的调用语法?
或者以不同的方式提出问题。如何在问号处获取枚举表示类型(在本例中为 u8),同时满足最后一行“::try_from”施加的“std::convert::From”要求?
pub fn extract_enum_bits<EnumType: TryFromPrimitive>(data: …Run Code Online (Sandbox Code Playgroud) 根据Rust FFI Omnibus,以下内容应该有效。
\n这是一个名为“foo”的 Rust cdylib,lib.rs用 Cargo build 制作...
use std::convert::From;\n\n// Rust FFI Omnibus: Tuples \n// http://jakegoulding.com/rust-ffi-omnibus/tuples/\n\n// A Rust function that accepts a tuple\nfn flip_things_around_rust(tup: (u32, u32)) -> (u32, u32) {\n let (a, b) = tup;\n (b + 1, a - 1)\n}\n\n// A struct that can be passed between C and Rust\n#[repr(C)]\npub struct Tuple {\n x: u32,\n y: u32,\n}\n\n// Conversion functions\nimpl From<(u32, u32)> for Tuple {\n fn from(tup: (u32, u32)) -> Tuple {\n Tuple …Run Code Online (Sandbox Code Playgroud) 我有一个 Node 类,以十六进制和 HSV 形式保存 RGB 数据。我将使用它以各种方式对颜色进行排序,并且希望 HSV 元组保持浮点形式进行比较,而不是每次使用时都从字符串进行转换。有没有一种方法可以指定数据类字段应该以类似于默认值的特定方式格式化值default_factory,即 a repr_factory?
def RGB2HSV(r, g, b):
'''Returns HSV values in the range H = [0, 360], S = [0, 100], V = [0, 100]'''
r, g, b = r / 255, g / 255, b / 255
maxRGB = max(r, g, b)
minRGB = min(r, g, b)
delta = maxRGB - minRGB
V = maxRGB
if V == 0:
return 0, 0, V
S = delta / V …Run Code Online (Sandbox Code Playgroud) 我最近了解到我们可以使用以下内容作为repr(x)Python 的简写:
`x`
Run Code Online (Sandbox Code Playgroud)
但是,我很少在实践中看到这一点.它被认为是不好的做法还是unpythonic?还是有其他原因很少使用?