我试图理解元类。
我已阅读json_decode,我尝试使用这样的自定义__call__
:
#!/usr/bin/env python3
class MetaTest(type):
def __call__(cls, *args, **kwargs):
print("MetaTest.__call__ called.")
return super().__call__(cls, *args, **kwargs)
class Test:
__metaclass__ = MetaTest
if __name__ == '__main__':
Test()
我希望在实例时调用Test.__class__.__call__
,Test.__class__
成为MetaTest
的实例,但事实并非如此,因为我没有运行此脚本时的输出。
那么为什么MetaTest.__call__
在Test
实施时被func createFirstRowView() {
let b = SKSpriteNode(imageNamed: "obj_bg_card1")
b.xScale = 0.8
b.yScale = 0.8
r = SKShapeNode(rectOf: CGSize(width: b.size.width*4, height: b.size.height))
r.position = CGPoint(x: frame.midX, y: frame.midY)
//r.strokeColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.addChild(r)
for i in 0..<4{
let bg = SKSpriteNode(imageNamed: "obj_bg_card1")
bg.xScale = 0.8
bg.yScale = 0.8
let lel = 0.5 + (Double(i)*1)
bg.position = CGPoint(x: -bg.size.width*2 + bg.size.width*CGFloat(lel), y: 0)
r.addChild(bg)
}
r.position = CGPoint(x: frame.midX, y: frame.midY*1.4)
let q = SKSpriteNode(imageNamed: "obj_bg_card1")
q.xScale = 0.8
q.yScale = 0.8
t = SKShapeNode(rectOf: CGSize(width: q.size.width*4, height: q.size.height))
t.position = CGPoint(x: frame.midX, y: frame.midY)
//t.strokeColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.addChild(t)
for k in 0..<4{
let bg = SKSpriteNode(imageNamed: "obj_bg_card1")
bg.xScale = 0.8
bg.yScale = 0.8
let lel = 0.5 + (Double(k)*1)
bg.position = CGPoint(x: -bg.size.width*2 + bg.size.width*CGFloat(lel), y: 0)
t.addChild(bg)
}
t.position = CGPoint(x: frame.midX, y: frame.midY*0.6)
}
调用?
答案 0 :(得分:1)
您正在为元类使用Python 2语法 - 但您的shebang行和标记表明您在Python 3上运行它。
只需更改您的类声明,即可使用Python&#39;声明元类。 3路:
#!/usr/bin/env python3
class MetaTest(type):
def __call__(cls, *args, **kwargs):
print("MetaTest.__call__ called.")
return super().__call__(cls, *args, **kwargs)
class Test(metaclass=MetaTest):
pass
if __name__ == '__main__':
Test()
在类体上声明__metaclass__
属性在Python 3-中没有任何效果,但由于它只是一个属性声明,因此它也不会引发任何错误。