了解Python对象和类的工作方式

2024-05-28 23:04:28 发布

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

我试图遵循《物理中的有效计算》的指导,这是一本Python研究的现场指南(由Anthony Scopatz和Kathryn Duff编写)。在OOP章节(特别是我版本的第136页),我尝试复制代码并运行以下代码:

# import the Particle class from the particle module
from particle import Particle as p
# create an empty list to hold observed particle data
obs = []
# append the first particle
obs.append(p.Particle())
# assign its position
obs[0].r = {'x': 100.0, 'y': 38.0, 'z': -42.0}
# append the second particle
obs.append(p.Particle())
# assign the position of the second particle
obs[1].r = {'x': 0.01, 'y': 99.0, 'z': 32.0}
# print the positions of each particle
print(obs[0].r)
print(obs[1].r)

结果应该是输入的位置。但是,代码不是这样工作的。相反,我使用了代码,而此代码起了作用:

# Import the Particle class from the particle Module
from particle import Particle as p

# Create an empty list
obs = []

# Append first element
obs.append(p)

# Assign its position
obs[0].r = {'x': 100.0, 'y': 38.0, 'z': -42.0}

# Append second particle
obs.append(particle())

# Assign second position
obs[1].r = {'x': 0.01, 'y': 99.0, 'z': 32.0}

print(obs[0].r)
print(obs[1].r)

我很想了解为什么会这样,为什么会这样。我现在正在回顾OOP是如何工作的,并且正在使用Python。请回答!我想了解这是如何工作的,为什么工作的


Tags: the代码fromimportanaspositionoop
1条回答
网友
1楼 · 发布于 2024-05-28 23:04:28

我不确定我是否理解所有内容,但如果您想在POO中转换代码,可以尝试以下方法:

from particle import Particle as p

class Myclass:
    def __init__(self):
        # Create an empty list
        self.obs = []
        # Append first element
        self.obs.append(p)

        # Assign its position
        self.obs[0].r = {'x': 100.0, 'y': 38.0, 'z': -42.0}

        # Append second particle
        self.obs.append(particle())

        # Assign second position
        self.obs[1].r = {'x': 0.01, 'y': 99.0, 'z': 32.0}
    
        #if you want to call getobs from here use :
        #self.getobs1()

    def getobs0(self):
        print(self.obs[0].r)

    def getobs1(self):
        print(self.obs[1].r)
    
if __name__ == '__main__':
    myClass = Myclass() #create an object of Myclass and call __init__()
    myClass.getobs0()
    myClass.getobs1()

相关问题 更多 >

    热门问题