我正在学习python,下面知道我在做什么是正确的,还是有更好的书写方式?
class FUNC:
def __init__(self,a,b):
self.a = a
self.b = b
def Add(self):
x = self.a + self.b
return x
def Sub(self):
y = self.a - self.b
return y
class TASKS:
def tsk1(self):
PrintObj1 = FUNC(10,20)
print(PrintObj1.Add())
def tsk2(self):
PrintObj2 = FUNC(100,50)
print(PrintObj2.Sub())
class RUNTASK:
Obj = TASKS()
Obj.tsk1()
Obj.tsk2()
答案 0 :(得分:1)
是的,您的代码看起来正确,但是您也可以使用仅包含静态方法的TASKS
类。静态方法是属于类而不是类实例的方法,因此您无需创建类的实例即可调用静态方法(在这种情况下很方便):
class FUNC:
def __init__(self,a,b):
self.a = a
self.b = b
def Add(self):
x = self.a + self.b
return x
def Sub(self):
y = self.a - self.b
return y
class TASKS:
@staticmethod
def tsk1():
PrintObj1 = FUNC(10,20)
print(PrintObj1.Add())
@staticmethod
def tsk2():
PrintObj2 = FUNC(100,50)
print(PrintObj2.Sub())
TASKS.tsk1()
TASKS.tsk2()
答案 1 :(得分:1)
您在这里要做的是在类的方法内创建另一个类的对象。如果您想证明(quantiles, values), (slope, intercept, r) = probplot(datafl.data[varcol], dist='norm')
fig = plt.figure(figsize=(5,4))
ax = fig.add_subplot(111)
ax.plot(values, quantiles, 'k.')
ax.set_xlabel('AuFA (opt)')
ax.set_xscale('log')
ax.set_xlim((lower, upper))
ax.xaxis.set_major_formatter(FormatStrFormatter('%1.4f'))
subs = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
类完全属于plt.grid(b=True, which='minor', color='lightgray', linestyle='-')
plt.grid(b=True, which='major', color='lightgray', linestyle='-')
ax.set_ylabel('Cumulative Probability')
ticks_perc=[0.01, 0.1, 1, 5, 10, 20, 50, 80, 80, 90, 95, 99, 99.9, 99.99]
ticks_quan=[scipy.stats.norm.ppf(i/100.) for i in ticks_perc]
plt.yticks(ticks_quan,ticks_perc)
print(ticks_quan)
print(ticks_perc)
if (threshflname is not None) and (domain is not None):
with open(threshflname, 'r') as infl:
for line in infl:
if line.startswith(domain):
numthresholds = int(line.split(' ')[2])
lower_upper = next(infl)
lower = float(lower_upper.split(' ')[1])
upper = float(lower_upper.split(' ')[3])
thresholds = next(infl)
thresholds = [float(thresh) for thresh in thresholds.split(' ')[1].split(',')]
break
for threshold in thresholds:
#Interpolate the cumulative probability
cumprob = np.interp(threshold, values, quantiles)
#ax.plot([threshold, threshold, ax.get_xlim()[0]], [ax.get_ylim()[0], cumprob, cumprob], color=colour_thresholds1, lw=0.8)
ax.plot([threshold, threshold, ax.get_xlim()[0]], [ax.get_ylim()[0], cumprob, cumprob], color=colour_thresholds1, lw=0.8)
cumprob = np.interp(lower, values, quantiles)
ax.plot([ax.get_xlim()[0], lower, lower], [cumprob, cumprob, ax.get_ylim()[0]], color=colour_thresholds2, ls='--', lw=0.8)
cumprob = np.interp(upper, values, quantiles)
ax.plot([ax.get_xlim()[0], upper, upper], [cumprob, cumprob, ax.get_ylim()[0]], color=colour_thresholds2, ls='--', lw=0.8)
plt.title('{} Indicator Thresholds'.format(domain.upper()))
,则可以这样做:
FUNC
这称为内部或嵌套类。在Python中不是特别常见。另外,我已经展示了两种访问内部类的方法,一种是使用实例方法,另一种是使用@ArtsiomPraneuski建议的静态方法(在这里似乎更合适)。