繁体   English   中英

Python class 属性错误,即使属性在 __init__ 中

[英]Python class Attribute Error even though attribute is in __init__

我正在尝试运行我的程序:

from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController

app = Ursina()
window.fullscreen = True

class Voxel(Button):
    def __init__(self, colour, position = (0, 0, 0)):
        super().__init__(
            parent  = scene,
            position = position,
            model = "cube",
            orgin_y = 0.5,
            texture = "white_cube",
            color = colour,
            )

    def start_game(self):
        self.colour = color.white

    def input(self, key):
        if self.hovered:
            if key == "right mouse up":
                voxel = Voxel(position = self.position + mouse.normal, colour = self.colour)

            if key == "left mouse up":
                destroy(self)

            if key == "0":
                self.colour = color.white

            if key == "1":
                self.colour = color.lime

for z in range(22):
    for x in range(22):
        voxel = Voxel(position = (x, 0, z), colour = color.lime)
        voxel.start_game()

player = FirstPersonController()
app.run()

我正在使用 python 3.10.6 和空闲。

当我运行该程序时,它按预期工作,除非我在放置一个块后选择绿色时它变成白色。 如果我垃圾邮件点击我得到错误:

  File "C:\Users\game.py", line 24, in input
    voxel = Voxel(position = self.position + mouse.normal, colour = self.colour)
AttributeError: 'Voxel' object has no attribute 'colour'

此代码似乎在多个地方同时使用了colorcolour

看起来ursina库使用color形式

我建议在您的代码中随处使用color ,以与您使用的库保持一致。 如果您需要在拼写之间进行转换并记住在哪个地方使用哪个版本,那么维护起来会更加困难。

此外,即使他们的示例可能使用from ursina import *这样做也不是最佳实践,因为这会让人不清楚名称空间中可用的名称。 最好明确地执行from ursina import Ursina, Button, window

使用 self.colour 时以及调用 Voxel 时,您使用的是颜色而不是颜色。

你应该做:

voxel = Voxel(position = self.position + mouse.normal, colour = self.color)

和:

self.color = color

解决方案是在代码中用颜色替换颜色。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM