python-3.x - 类变量拒绝通过“self”工作,但使用类名(Python)
问题描述
我在这个类中有一个简单的类和一个类变量:
class QuotesToScrape:
authors_list = []
def __init__:
此类内部的方法中有一行代码(方法从init调用):
def gather_authors_list(self):
self.authors_list = some_value
此行不起作用,变量 authors_list 仍然为空。但是,如果我将“self”更改为类名,它就可以正常工作:
def gather_authors_list(self):
QuotesToScrape.authors_list = some_value
没有使用装饰器。我觉得这是我需要了解的一些重要技巧,以防止我将来出现严重问题。
稍后添加。重要部分:我有另一个类变量“quotes”,它工作得很好。这是我的代码的几乎完整片段。类变量“quotes”正常,类变量“authors_list”不正常。
class QuotesToScrape:
quotes = []
authors_list = []
def __init__(self):
for page_number in range(1, 501):
page_url = self.make_page_url(page_number)
soup = self.get_soup(page_url)
if self.out_of_quotes(soup):
break
quote_blocks = self.parse_quotes(soup)
for quote_block in quote_blocks:self.quotes
quote = self.extract_quote(quote_block)
self.quotes.append(quote)
self.gather_authors_list()
...
def gather_authors_list(self):
authors = list(set([quote.get('Author') for quote in self.quotes]))
if 'Alexandre Dumas fils' in authors:
duma_index = authors.index('Alexandre Dumas fils')
authors[duma_index] = 'Alexandre (fils) Dumas'
self.authors_list = sorted(authors, key = lambda x: x.split(" ")[-1])
稍后添加。问题解决了。更改了最后一行以匹配评论中的指示。这解决了我的问题,now 方法不会创建新变量,而是使用现有的空类变量:
self.authors_list.extend(sorted(authors, key = lambda x: x.split(" ")[-1]))
解决方案
在有问题的版本后编辑:当您说self.authors_list = ...
类变量没有得到更新时,而是创建了一个新的对象变量,并且它仅适用于该类实例。在 的情况下quotes
,您正在执行任何分配,而是执行附加,该附加会反映在类变量quotes
中。
当您这样做时QuotesToScrape.authors_list
,您更改了类变量,并且此获取反映在您之后创建的其他对象实例中。
尝试通过以下示例了解您的情况:
class Yes:
a = 1
def __init__(self):
pass
def yes(self):
if Yes.a==1:
print "Yes"
else:
print "No, but yes"
class No(Yes):
def no(self):
if Yes.a==1:
print "No"
else:
print "Yes, but no"
Yes.a-=1 #Note this line
Yes().yes()
No().no()
Yes().yes()
No().no()
这个问题的答案是:
Yes().yes()
No().no()
Yes().yes()
No().no()
我希望通过这个例子可以帮助你理解类变量的知识。如果您有任何疑问,请告诉我。:)
推荐阅读
- scala - Def 宏,从一个值传递参数
- python - 名称 other_script 未定义
- reactjs - Redux-saga 没有在我的 reactJS 应用程序中运行
- scala - 如何使 scala 2.12.11 代码在 scala 2.13.2 中运行?
- kubernetes - OPA Gatekeeper 可以用来审计 K8s PodDisruptionBudget 状态字段吗?
- javascript - 反应 javascript 获取 python
- web - Recaptcha - 在不同的应用程序中使用相同的站点密钥是否安全/良好的做法
- python-3.x - vtkOBJReader 对象没有 Object (.obj) 文件的属性 SetFileNameMTL (.mtl)
- c# - C#中使用网络信息的网线状态
- c# - 无法访问 GridView -> TemplateField -> EditItemTemplate 中的某些元素的问题