繁体   English   中英

如何使用类来缩短此代码?

[英]How can I use classes to shorten this code?

我花了数小时试图建立一个类,在该类中输入一个与太阳距离最大和最小的行星(M和m),然后该类将在具有正确椭圆的网格上打印出椭圆。

到目前为止,我有这个:

import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
#Set axes aspect to equal as orbits are almost circular.
ax = plt.figure(0).add_subplot(111, aspect='equal')

#Setting the title, axis labels, axis values and introducing a grid underlay
#Variable used so title can indicate user inputed date
plt.title('Inner Planetary Orbits at[user input date]')
plt.ylabel('x10^6 km')
plt.xlabel('x10^6 km')
ax.set_xlim(-300, 300)
ax.set_ylim(-300, 300)
plt.grid()

#Creating the sun circle at the origin (not to scale), 
#intended to remain at a constant position and size so no variables are needed
ax.scatter(0,0,s=200,color='y')
plt.annotate('Sun', xy=(0,-30))

#Generate test ellipses 'Mercury' and 'Earth'


class PlanetOrbit:
    def __init__(self, name, M, m):
        self.name=name
        self.M=M
        self.m=m
        self.width=0
        self.height=0

    def OrbitLength(self):
        a=(self.M+self.m)/2
        c=a-self.m
        e=c/a
        b=((a**2)*(1-(e**2)))**0.5

        return b, a


    def WidthHeight(self, x, y):
        Width=2*x
        Height=2*y
        return Width, Height


x, y=PlanetOrbit('test',100,25).OrbitLength()
MercuryWidth, MercuryHeight=PlanetOrbit('test',100,25).WidthHeight(x, y)

x, y=PlanetOrbit('test',100,140).OrbitLength()
VenusWidth, VenusHeight=PlanetOrbit('test',100,40).WidthHeight(x, y)


Mercury = [Ellipse(xy=(0,0),width=MercuryWidth, height=MercuryHeight,angle=0, linewidth=1, fill=False)]

for e in Mercury:
    ax.add_artist(e)

Venus =  [Ellipse(xy=(0,0),width=VenusWidth, height=VenusHeight,angle=0, linewidth=1, fill=False)]

for e in Venus:
    ax.add_artist(e)




plt.show()

这是可行的,但此项目的目的是减少功能重复等的次数。

我对课堂的理解不够充分,无法进一步改进。 任何建议将不胜感激。

谢谢

如果我错了,请纠正我,但是在此应用程序中,似乎您只是在尝试打印出网格的月食。 由于这只是一项简单的任务,因此您只适合使用几种方法。 如果您查看WidthHeight方法,则永远不会使用类中的任何变量,仅使用您的参数,因此该变量应在类之外或至少是静态的。 就像是

def orbitLength(M, m):
    a=(M+m)/2
    c=a-m
    e=c/a
    b=((a**2)*(1-(e**2)))**0.5

    return b, a


def PlanetOrbit(name, M, m):
    w, h = orbitLength(M, m)
    e = Ellipse(xy=(0,0), width=w, height=h, angle=0, linewidth=1, fill=False)
    ax.add_artist(e)

然后,您可以像PlanetOrbit('test',100,140)这样简单地调用它PlanetOrbit('test',100,140)它会与当前代码执行相同的操作。 学习如何使用类很好,但是有时您还需要知道什么时候不使用它们。

暂无
暂无

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

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