在 __init__ 中使用函数和实例方法定义实例变量
Defining instance variables using functions and instance methods in __init__
我将以下 class 定义为:
def user_kitchen(handle):
# return a BeautifulSoup object
class User(object):
def __init__(self, handle):
self.handle = str(handle)
self.soup = user_kitchen(handle)
self.details = self.find_details()
def find_details(self):
value_map = {}
for detail, attribute in details_map:
value = (self.soup).find_all(attrs=attribute)[0].text
value_map[detail] = value
return value_map
当我将 class User
实例化为:
me = User('torvalds')
我得到一个 NameError: name 'self' is not defined
这是回溯:
In []: me = User('torvalds')
NameError Traceback (most recent call last)
<ipython-input-61-f6d334f2ee24> in <module>()
----> 1 me = User('torvalds')
/home/user.py in __init__(self, handle)
28 value_map = {}
29 for detail, attribute in details_map:
---> 30 value = (self.soup).find_all(attrs=attribute)[0].text
31 value_map[detail] = value
32 return value_map
/home/user.py in _find_details(detail)
18
19
---> 20 class User(object):
21
22 def __init__(self, handle):
NameError: name 'self' is not defined
我在 SO 上看过一些关于从 __init__
方法调用实例方法的类似问题:
Calling a class function inside of init
Python: How to define a variable in an init function with a class method?
但是我无法解决这个问题。
根据您的堆栈跟踪,我看到一个带有签名的方法 - _find_details(detail)
。在那个方法里面,有一行像 - value = (self.soup).find_all(attrs=attribute)[0].text
。
您的方法没有将 self
作为第一个参数。所以它在那个上下文中找不到 self
。让它 _find_details(self, detail)
- 然后它应该工作。
我将以下 class 定义为:
def user_kitchen(handle):
# return a BeautifulSoup object
class User(object):
def __init__(self, handle):
self.handle = str(handle)
self.soup = user_kitchen(handle)
self.details = self.find_details()
def find_details(self):
value_map = {}
for detail, attribute in details_map:
value = (self.soup).find_all(attrs=attribute)[0].text
value_map[detail] = value
return value_map
当我将 class User
实例化为:
me = User('torvalds')
我得到一个 NameError: name 'self' is not defined
这是回溯:
In []: me = User('torvalds')
NameError Traceback (most recent call last)
<ipython-input-61-f6d334f2ee24> in <module>()
----> 1 me = User('torvalds')
/home/user.py in __init__(self, handle)
28 value_map = {}
29 for detail, attribute in details_map:
---> 30 value = (self.soup).find_all(attrs=attribute)[0].text
31 value_map[detail] = value
32 return value_map
/home/user.py in _find_details(detail)
18
19
---> 20 class User(object):
21
22 def __init__(self, handle):
NameError: name 'self' is not defined
我在 SO 上看过一些关于从 __init__
方法调用实例方法的类似问题:
Calling a class function inside of init
Python: How to define a variable in an init function with a class method?
但是我无法解决这个问题。
根据您的堆栈跟踪,我看到一个带有签名的方法 - _find_details(detail)
。在那个方法里面,有一行像 - value = (self.soup).find_all(attrs=attribute)[0].text
。
您的方法没有将 self
作为第一个参数。所以它在那个上下文中找不到 self
。让它 _find_details(self, detail)
- 然后它应该工作。