简单Python类定义不起作用
在下面的代码中,编译器给了我一个错误:赋值前引用的局部变量shouldStoreData。但我先分配它简单Python类定义不起作用,python,Python,在下面的代码中,编译器给了我一个错误:赋值前引用的局部变量shouldStoreData。但我先分配它 class MyHTMLParser(HTMLParser): shouldStoreData = False textPartDoc = "" def handle_starttag(self, tag, attrs): print "Encountered a start tag:", tag if(tag == "title" or
class MyHTMLParser(HTMLParser):
shouldStoreData = False
textPartDoc = ""
def handle_starttag(self, tag, attrs):
print "Encountered a start tag:", tag
if(tag == "title" or tag == "body"):
shouldStoreData = True
def handle_endtag(self, tag):
print "Encountered an end tag :", tag
def handle_data(self, data):
#print "Data is",data
#print "valus of storeData is:",shouldStoreData
if(shouldStoreData == True):
textPartDoc = textPartDoc + " " + data
shouldStoreData = False
这里我要做的是,我只想在标记是title或body中的任何标记时存储数据。第一个shouldStoreData是class属性。handle_starttag和handle_data中的是局部变量。在handle_data中,在分配变量之前测试变量。方法中的代码不知道class属性是否存在,除非您以类/实例属性(例如self.shouldStoreData或MyHTMLParser.shouldStoreData)的形式明确访问它
如果希望shouldStoreData成为实例属性,则需要编写一个_init__方法并将其创建为实例属性:
def __init__(self):
self.shouldStoreData = False
然后在其他方法中将其称为self.shouldStoreData
您应该阅读以掌握Python中类、属性和方法的基本知识。第一个shouldStoreData是类属性。handle_starttag和handle_data中的是局部变量。在handle_data中,在分配变量之前测试变量。方法中的代码不知道class属性是否存在,除非您以类/实例属性(例如self.shouldStoreData或MyHTMLParser.shouldStoreData)的形式明确访问它
如果希望shouldStoreData成为实例属性,则需要编写一个_init__方法并将其创建为实例属性:
def __init__(self):
self.shouldStoreData = False
然后在其他方法中将其称为self.shouldStoreData
您应该阅读本书以掌握Python中类、属性和方法的基本知识。一个简单的示例使其更加清晰:
x='outside'
class A:
x='inside'
def __init__(self):
print x #prints the global x
def func1(self):
x='changed' #changes the global x
print x,A.x #prints the global x and then the class's x
输出:
下面是一个简单的例子,让我们更清楚地了解:
x='outside'
class A:
x='inside'
def __init__(self):
print x #prints the global x
def func1(self):
x='changed' #changes the global x
print x,A.x #prints the global x and then the class's x
输出:
无法在python 2.7.3上复制。您使用的是什么版本?无法在python 2.7.3上复制。您使用的是什么版本?实例属性与类相同吗attribute@Programmer:否。实例属性特定于该实例。类属性是特定于该类的。再次阅读Python教程,熟悉Python.Wow中类的工作方式。简言之,类属性为何如此?类定义不创建名称空间吗?@Programmer-它们很相似。类属性绑定到类,而不是类的实例。只要特定实例通过instance.attribute没有相同名称的属性,实例就可以访问class属性。@LevLevitsky:类定义创建了一个命名空间,但类中的方法代码没有对该类命名空间的直接隐式访问权。他们必须使用类的名称显式地访问它。实例属性与类相同吗attribute@Programmer:否。实例属性特定于该实例。类属性是特定于该类的。再次阅读Python教程,熟悉Python.Wow中类的工作方式。简言之,类属性为何如此?类定义不创建名称空间吗?@Programmer-它们很相似。类属性绑定到类,而不是类的实例。只要特定实例通过instance.attribute没有相同名称的属性,实例就可以访问class属性。@LevLevitsky:类定义创建了一个命名空间,但类中的方法代码没有对该类命名空间的直接隐式访问权。他们必须使用类的名称显式地访问它。