我目前正在使用@property装饰器在我的几个课程中实现"getter and setters".我希望能够@property在子类中继承这些方法.
我有一些Python代码(具体来说,我在py3k中工作),看起来有点模糊:
class A:
@property
def attr(self):
try:
return self._attr
except AttributeError:
return ''
class B(A):
@property
def attr(self):
return A.attr # The bit that doesn't work.
@attr.setter
def attr(self, value):
self._attr = value
if __name__ == '__main__':
b = B()
print('Before set:', repr(b.attr))
b.attr = 'abc'
print(' After set:', repr(b.attr))
Run Code Online (Sandbox Code Playgroud)
我已经标记了与评论无关的部分.我希望返回基类'attr getter.A.attr返回一个属性对象(可能非常接近我需要的东西!).
编辑:
在从Ned收到以下答案后,我想到了我认为对这个问题更优雅的解决方案.
class A:
@property
def attr(self):
try:
return self._attr
except AttributeError:
return ''
class B(A):
@A.attr.setter
def …Run Code Online (Sandbox Code Playgroud) 我目前在使用XHTML读取时遇到问题,因为XML解析器无法识别HTML字符实体,因此:
<?php
$text = <<<EOF
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Entities are Causing Me Problems</title>
</head>
<body>
<p>Copyright © 2010 Some Bloke</p>
</body>
</html>
EOF;
$imp = new DOMImplementation ();
$html5 = $imp->createDocumentType ('html', '', '');
$doc = $imp->createDocument ('http://www.w3.org/1999/xhtml', 'html', $html5);
$doc->loadXML ($text);
header ('Content-Type: application/xhtml+xml; charset: utf-8');
echo $doc->saveXML ();
Run Code Online (Sandbox Code Playgroud)
结果是:
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Entity 'copy' not defined in Entity, line: 8 in testing.php on line 19
如何在允许自己将页面作为XHTML5提供的同时解决这个问题?
考虑以下生日(as dob):
用Python解析时datetime.strptime(dob, '%d-%b-%y')会产生:
datetime.datetime(2068, 6, 1, 0, 0)datetime.datetime(1969, 6, 1, 0, 0)当然,他们应该出生在同一个十年,但现在甚至不是在同一个世纪!
根据文档,这是完全有效的行为:
当接受2位数年份时,它们将根据POSIX或X/Open标准进行转换:值69-99映射到1969-1999,值0-68映射到2000-2068.
我理解为什么函数设置这样,但是有办法解决这个问题吗?也许定义自己的两位数年份范围?
我已经能够将其表达为一个函数,以便foo返回末尾不带“Bar”的字符串。但是,如何使用该type语句来管理同样的事情呢?(见下文)
declare function foo<T extends string>(str: `${T}Bar`): T;
const justFoo = foo('fooBar');
// justFoo now exactly matches the type 'foo'
// What goes here?
type Foo<T extends string> = T;
type JustFoo = Foo<'fooBar'>;
Run Code Online (Sandbox Code Playgroud) python ×2
2-digit-year ×1
domdocument ×1
entities ×1
html5 ×1
php ×1
properties ×1
strptime ×1
typescript ×1
xml ×1