标签: attributeerror

Python 中处理 AttributeError 的特殊方法是什么?

我应该在我的类中重新定义什么特殊方法,以便它处理AttributeError异常并在这些情况下返回一个特殊值?

例如,

>>> class MySpecialObject(AttributeErrorHandlingClass):
      a = 5
      b = 9
      pass
>>>
>>> obj = MySpecialObject()
>>>
>>> obj.nonexistent
'special value'
>>> obj.a
5
>>> obj.b
9
Run Code Online (Sandbox Code Playgroud)

我用谷歌搜索答案,但找不到。

python attributeerror

3
推荐指数
1
解决办法
1835
查看次数

Python:又一个AttributeError:'module'对象没有属性

我尝试阅读其他一些问题,但我仍然无法让它发挥作用.

基本上我正在使用一个名为time_string()的快速而脏的函数来返回以我想要的方式格式化的字符串中的日期和时间.如果我直接运行time_string,它工作正常.如果我从另一个函数调用它,我会得到一个AttributeError.

TIME_STRING

import time
def time_string(): #Never mind the unreadable formatting
    return str(time.localtime().tm_hour)+':'+str(time.localtime().tm_min)+':'+str(time.localtime().tm_sec)+\
           ' '+str(time.localtime().tm_year)+'/'+str(time.localtime().tm_mon)+'/'+str(time.localtime().tm_mday)

if __name__ == '__main__':
    print time_string()
Run Code Online (Sandbox Code Playgroud)

直接运行time_string

2012/7/19 13:46:13

其他功能

from misc.time_string import time_string
def main():
    print time_string()

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

运行其他功能

回溯(最近调用最后一次):文件"#Filepath#",第10行,在main()文件"#Filepath#",第7行,在主打印time_string()文件"#Filepath#",第9行,在time_string中''+ str(time.localtime().tm_year)+'/'+ str(time.localtime().tm_mon)+'/'+ str(time.localtime().tm_mday)AttributeError:'module'对象有没有属性'localtime'

我假设它有一些问题,时间没有进口或什么,但它是令人难以置信的

谢谢您的帮助!

python attributeerror

3
推荐指数
1
解决办法
2万
查看次数

Python 错误:“NoneType”对象没有属性“find_all”

我正在改编来自http://danielfrg.com/blog/2013/04/01/nba-scraping-data/#disqus_thread的网络抓取程序,以将 ESPN 的棒球数据抓取到 CSV 中。但是,当我运行第二段代码来编写一个 csv 游戏时,我从以下代码部分得到“NoneType”对象没有属性“find_all”错误

for index, row in teams.iterrows():
    _team, url = row['team'], row['url']
    r = requests.get(BASE_URL.format(row['prefix_1'], year, row['prefix_2']))
    table = BeautifulSoup(r.text).table
    for row in table.find_all("tr")[1:]: # Remove header
        columns = row.find_all('td')
        try:
            _home = True if columns[1].li.text == 'vs' else False
            _other_team = columns[1].find_all('a')[1].text
            _score = columns[2].a.text.split(' ')[0].split('-')
            _won = True if columns[2].span.text == 'W' else False

            match_id.append(columns[2].a['href'].split('?id=')[1])
            home_team.append(_team if _home else _other_team)
            visit_team.append(_team if not _home else _other_team)
            d = datetime.strptime(columns[0].text, '%a, %b …
Run Code Online (Sandbox Code Playgroud)

python object attributeerror nonetype

3
推荐指数
1
解决办法
4万
查看次数

如何在Beautiful Soup中找到所有段落中的所有链接

假设您在 python 解释器中输入了以下内容:

from urllib import request
from bs4 import BeautifulSoup
soup = BeautifulSoup(request.urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)").read())
a = soup.find_all('p')
b = a.find_all('href')
Run Code Online (Sandbox Code Playgroud)

我希望 b 是段落中所有链接的列表,但是,它给出了一个属性错误,其中 a 是“ResultSet”并且没有属性“find_all”。如何使用 BeautifulSoup 找到段落中的所有链接?

python urllib beautifulsoup attributeerror

3
推荐指数
1
解决办法
2286
查看次数

win32com.client:AttributeError:wdHeaderFooterPrimary和AttributeError:wdAlignParagraphCenter

我们准备以下python脚本以在单词表中显示图片。

import matplotlib.pyplot as plt
import pylab 
import win32com.client as win32  
import os

# Skip picture making parts

#Generate word file
#Create and formating
wordapp = win32.Dispatch("Word.Application") #create a word application object

wordapp.Visible = 1 # hide the word application

doc=wordapp.Documents.Add() 

# create a new application

doc.PageSetup.RightMargin = 20

doc.PageSetup.LeftMargin = 20

doc.PageSetup.Orientation = 1

# a4 paper size: 595x842

doc.PageSetup.PageWidth = 595
doc.PageSetup.PageHeight = 842

header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range

header_range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter

header_range.Font.Bold = True

header_range.Font.Size = 12

header_range.Text = "" …
Run Code Online (Sandbox Code Playgroud)

python attributeerror win32com

3
推荐指数
1
解决办法
3719
查看次数

使用**kwargs设置属性时的Python3 AttributeError

简单地说,我明白为什么我不能使用这样的for循环设置属性**kwargs:

class Person():
    def __init__(self, onevar, *args, **kwargs):
        self.onevar = onevar
        for k in kwargs:
            self.k = kwargs[k]
            print(k, self.k)   

def run():
    ryan = Person('test', 4, 5, 6, name='ryan', age='fifty')
    print(ryan.name)

def main():
    run()

if __name__=="__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

这将返回以下内容:

AttributeError: 'Person' object has no attribute 'name'
Run Code Online (Sandbox Code Playgroud)

谁知道为什么?

python attributeerror

3
推荐指数
1
解决办法
613
查看次数

Python - AttributeError: 'str' 对象没有属性 'items'

我是Tkinter. 我正在尝试制作电话簿 GUI 应用程序。

所以,我才刚刚开始,这是我的源代码:

#This is my python 'source.py' for learning purpose

from tkinter import Tk
from tkinter import Button
from tkinter import LEFT
from tkinter import Label
from tkinter import Frame
from tkinter import Pack

wn = Tk()
f = Frame(wn)

b1 = Button(f, "One")
b2 = Button(f, "Two")
b3 = Button(f, "Three")

b1.pack(side=LEFT)
b2.pack(side=LEFT)
b3.pack(side=LEFT)

l = Label(wn, "This is my label!")

l.pack()
l.pack()

wn.mainloop()
Run Code Online (Sandbox Code Playgroud)

当我运行时,我的程序出现以下错误:

/usr/bin/python3.4 /home/rajendra/PycharmProjects/pythonProject01/myPackage/source.py
Traceback (most recent call last):
  File "/home/rajendra/PycharmProjects/pythonProject01/myPackage/source.py", …
Run Code Online (Sandbox Code Playgroud)

python tkinter attributeerror

3
推荐指数
1
解决办法
7576
查看次数

'ReverseManyToOneDescriptor'对象没有属性'latest'

尝试运行函数时收到此错误.这是我的第一个django/python项目,所以我没有经验.我已经搜索过这个错误,但没有找到类似的东西.

def getpriority(chunks):
    p = 0
    for chunk in chunks:
        a = chunk.result_set.all()
        l = a.latest()
        if pytz.utc.localize(datetime.now()) - l.timestamp > datetime.timedelta(days=3):
            x = getresult(chunk)
            print(x)
Run Code Online (Sandbox Code Playgroud)

我正在尝试为我的Chunk模型分配优先级,以便我可以选择具有最高优先级的Chunk来使用该对象.

我相信我的错误在于呼唤latest()'a'.

当我在django shell中运行Chunk.result_set.latest()时,我收到以下错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'latest'
Run Code Online (Sandbox Code Playgroud)

在我的Result模型中,我设置了get_latest_by,我认为需要运行.latest():

class Result(models.Model):
    rel_chunk = models.ForeignKey(Chunk, on_delete=models.CASCADE)
    score = models.IntegerField()
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        get_latest_by = 'timestamp'
Run Code Online (Sandbox Code Playgroud)

我相信错误在于我在相关对象集上调用最新但如果无法在相关对象集上调用,那么如何才能找到最新的相关结果?

python django attributeerror

3
推荐指数
2
解决办法
3258
查看次数

Python记录到控制台

我正在尝试在Python 3.x中创建一个日志,该日志写到控制台。这是我的代码:

import logging
import sys

class Temp:
    def __init__(self, is_verbose=False):
        # configuring log
        if (is_verbose):
            self.log_level=logging.DEBUG
        else:
            self.log_level=logging.INFO

        log_format = logging.Formatter('[%(asctime)s] [%(levelname)s] - %(message)s')
        logging.basicConfig(level=self.log_level, format=log_format)
        self.log = logging.getLogger(__name__)

        # writing to stdout
        handler = logging.StreamHandler(sys.stdout)
        handler.setLevel(self.log_level)
        handler.setFormatter(log_format)
        self.log.addHandler(handler)

        # here
        self.log.debug("test")

if __name__ == "__main__":
    t = Temp(True)
Run Code Online (Sandbox Code Playgroud)

如果输入“ here”之后的行,Python会引发错误:

[2019-01-29 15:54:20,093] [DEBUG] - test
--- Logging error ---
Traceback (most recent call last):
  File "C:\Programok\Python 36\lib\logging\__init__.py", line 993, in emit
    msg = self.format(record)
  File "C:\Programok\Python 36\lib\logging\__init__.py", line …
Run Code Online (Sandbox Code Playgroud)

python logging formatter attributeerror python-3.x

3
推荐指数
1
解决办法
2465
查看次数

Python:'{0.lower()}'。format('A')产生'str'对象没有属性'lower()'

在Python中,字符串有一个方法lower()

>>> dir('A')
[... 'ljust', 'lower', 'lstrip', ...]
Run Code Online (Sandbox Code Playgroud)

但是,当尝试时'{0.lower()}'.format('A'),响应指出:

>>> '{0.lower()}'.format('A')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'lower()'
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我理解为什么在这种情况下,上面的行会引发AttributeError吗?似乎它不应该是AttributeError,尽管我一定会误会。任何帮助了解这一点将非常欢迎!

编辑:我知道我不能在format调用内调用lower()方法(尽管如果可能的话,它会很整洁);我的问题是为什么这样做会引发AttributeError。在这种情况下,此错误似乎会引起误解。

python attributeerror

3
推荐指数
1
解决办法
320
查看次数