python2.7.5中类中带有属性的奇怪行为

2024-05-19 17:38:17 发布

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

我是新来用python创作的。 但是我在2.7版上有一个奇怪的行为。5。2.7.8或2.7.1或3没有问题,只有2.7。5

我在尝试使用我的类时出现了这个错误

# ./script_testing.py 
Linux
('CentOS Linux', '7.1.1503', 'Core')
Traceback (most recent call last):
  File "./script_testing.py", line 1204, in <module>
    print(x.DIST)
AttributeError: WhatsName instance has no attribute 'DIST'

我的代码:

import platform

class WhatsName():
    """Distributive version checking and soft installing"""
    def __init__(self):

        self.PLAT=platform.system()
        self.DISTRIB=platform.linux_distribution()

        if self.PLAT=='Linux' or self.PLAT=='Linux2':
            if self.DISTRIB[0]=='debian':
                self.DIST='Debian'
            elif self.DISTRIB[0]=='Ubuntu':
                self.DIST='Ubuntu'
            elif self.DISTRIB[0]=='CentOS':
                self.DIST='Centos'
            elif self.DISTRIB[0]=='Fedora':
                self.DIST='Fedora'
            elif 'SUSE' in self.DISTRIB[0]:
                self.DIST='Suse'
            elif self.DISTRIB[0]=='Slackware':
                self.DIST='Slackware'
            else:
                pass
        elif self.PLAT=='FreeBSD':
            self.DIST='FreeBSD'
        elif PLAT=='Windows':
            self.DIST='Windows'
        elif PLAT=='Darwin':
            self.DIST='MacOS'
        else:
            self.DIST='Unknown'

    def CheckSystem(self):
        pass

    def InstallSoft(self,x,y):
        pass


x=WhatsName()
print(x.PLAT)
print(x.DISTRIB)
print(x.DIST)     <== This string generates the error

所以,我不明白为什么DIST不是WhatsName类的属性。 为什么只在2.7.5版本上发生

在其他版本中,我得到了正常的结果:

"script_testing.py" 1233L, 26872C записано
:!python2.7 script_testing.py
Linux
('debian', '7.1', '')
Debian

Tags: pyselflinuxdistdefscriptpasstesting
1条回答
网友
1楼 · 发布于 2024-05-19 17:38:17

没有任何if语句与self.DISTRIB的第一个值匹配:

('CentOS Linux', '7.1.1503', 'Core')

字符串是'CentOS Linux',但您不测试该字符串,因此self.DIST从未设置

只测试字符串'CentOS'

elif self.DISTRIB[0]=='CentOS':
    self.DIST='Centos'

这一行永远不匹配,这条if...elif...语句中的其他测试也不匹配。因为这里没有else来设置self.DIST,所以最后会出现一个属性错误

你可以把那条线修好:

elif self.DISTRIB[0]=='CentOS Linux':
    self.DIST='Centos'

我也会在开始处设置self.DIST = 'Unknown',这样您就有了一个默认值,然后让您的if分支集确定一个更精确的值

相关问题 更多 >