在初始化中定义的类属性与类方法定义的属性

2024-04-24 21:31:46 发布

您现在位置:Python中文网/ 问答频道 /正文

根据我在下面代码中测试的内容,当我定义自我定位属性,当我试图将值赋给实例时,它不起作用。你知道吗

class Matter():
    """docstring for Matter"""

    def __init__(self):
        self.xcoord = 0
        self.ycoord = 0
        self.location = (self.xcoord, self.ycoord)

main = Matter()
#before changing values
print(main.xcoord, main.ycoord)

#changing values
main.xcoord = 5
main.ycoord = 10

print(main.xcoord, main.ycoord)
print(main.location)

输出:

  • 0 0个
  • 5月10日
  • (0,0)

你知道吗自我定位在这种情况下没有改变。但当我这么做的时候:

main = Matter()
# before changinv the values
print(main.xcoord, main.ycoord)
# changing the values
main.xcoord = 5
main.ycoord = 10
print(main.xcoord, main.ycoord)
print(main.location)


class Matter():
    """docstring for Matter"""

    def __init__(self):
        self.xcoord = 0
        self.ycoord = 0

    def set_location(self):
        self.location = (self.xcoord, self.ycoord)


main = Matter()

print(main.xcoord, main.ycoord)
main.xcoord = 5
main.ycoord = 10

Matter.set_location(main)
print(main.xcoord, main.ycoord)
print(main.location)

输出:

  • 0 0个
  • 5月10日
  • (5,10)

附加问题:我可以在类中创建的任何属性和方法都可以通过使用类中没有的不同函数来使用和修改? 我可能在属性和实例之间有混淆,但如果有人能澄清我将不胜感激!你知道吗

谢谢你!你知道吗


Tags: 实例定位self属性maindeflocationclass
1条回答
网友
1楼 · 发布于 2024-04-24 21:31:46

这就是属性的用途。你知道吗

想想像属性一样的方法这样的属性。你需要在被请求的时候计算一些东西,但是它得到的东西并不是一个真正的动作而是一个状态。那是一个财产。你知道吗

在这种情况下,您有:

class Matter():
    def __init__(self):
        self.x = 5
        self.y = 10

    @property
    def location(self):
        return (self.x, self.y)

现在您可以像使用属性一样使用location,而它仍然像方法一样工作。你知道吗

m = Matter()
m.location  # (5, 10)
m.x, m.y = (20, 40)
m.location  # (20, 40)

但是您不能通过属性设置。。。你知道吗

m.location = (40, 80)  # error

…除非你写了一个setter

# inside class Matter, after the code above
...
    @location.setter
    def location(self, newloc):
        self.x, self.y = newloc

现在你可以了,它会像你说的那样更新。你知道吗

m.location = (40, 80)
m.x  # 40
m.y  # 80
m.location  # (40, 80)

相关问题 更多 >