如果我有一个文件,foo.py包含内容:
import pandas as pd
class Marcher(object):
def __init__(self, p_path):
self.p_path = p_path
p_m = 'ID'
def first_call(self):
df_p = pd.read_csv(self.p_path, header=None)
return df_p
def p_to_i(self, p):
pii = p.set_index(self.p_m, drop=False).loc[p[self.p_m]]
return pii
m1 = p_to_i(first_call())
我想用这个做的是这样的:
test = Marcher(p_path='/some/path/to/file.csv')
test.m1
然而,当我尝试这个时,我得到了一个错误:
TypeError: first_call() takes exactly 1 argument (0 given)
答案 0 :(得分:2)
为什么你希望m1
成为类成员变量?只需像这样移动电话:
def __init__(self, path):
self.path = path
self.m1 = self.p_to_i(self.first_call())
答案 1 :(得分:2)
问题是您在创建实例之前尝试调用方法。以一个简单的Circle类为例:
import math
class Circle(object):
def __init__(self, radius):
self.radius = radius
def get_area(self):
return math.pi * self.radius ** 2
# You cannot do this because every circle can have a different radius
# area = get_area()
# But you can use a property
@property
def area(self):
return self.get_area()
print Circle(2).area
# 12.5663706144
print Circle(10).area
# 314.159265359
此外,有时人们喜欢缓存属性值以避免重新计算它们,看起来像这样:
class Circle(object):
# ...
_area = None
@property area(self):
if self._area is None:
self._area = self.get_area()
return self._area
此方法的缺点是Circle
不再是动态对象,创建实例后不应更新“radius”属性,因为该区域已缓存且不会更新。