在我们写Python代码时,有时候想看看一个对象所有属性(或方法),这个很简单,通过调用内置方法 dir( ) 就可以搞定,但是如果我们除了想知道其具有的属性(或方法),还想知道在对象该属性下的值呢,上个例子代码:
import numpy as np
from sklearn.linear_model import LinearRegression
x = np.random.randn(1000,5)
y = np.random.randn(1000)
lr = LinearRegression()
lr.fit(x,y)
print lr.score(x,y)
通过dir(lr)
,可以得到对象lr
的所有属性(或方法):
dir(lr)
['__abstractmethods__', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_abc_cache', '_abc_negative_cache', '_abc_negative_cache_version', '_abc_registry', '_center_data', '_decision_function', '_estimator_type', '_get_param_names', '_residues', '_set_intercept', 'coef_', 'copy_X', 'decision_function', 'fit', 'fit_intercept', 'get_params', 'intercept_', 'n_jobs', 'normalize', 'predict', 'rank_', 'residues_', 'score', 'set_params', 'singular_']
方法1:
通过eval()
方法就可以得到
lr
的所有属性值了:
for attr in dir(lr):
if '_' not in attr:
print eval('lr.%s'%attr)
方法2:
for attr in dir(lr):
if '_' not in attr:
print getattr(lr, attr)
两个的输出都是:
<bound method LinearRegression.fit of LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)>
False
<bound method LinearRegression.predict of LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)>
<bound method LinearRegression.score of LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)>
至于eval()的使用可以参考:http://www.cnblogs.com/yyds/p/6276746.html?utm_source=itdadao&utm_medium=referral ,这个讲的蛮好的。
如果想把里面的函数方法也给输出可以试试这个:
import datetime
now = datetime.datetime.now()
for method in dir(now):
if '_' not in method:
if not hasattr(getattr(now, str(method)),'__call__'):
print '%s: %s'%(method,getattr(now, str(method)))
elif hasattr(getattr(now, str(method)), '__call__'):
try:
print method, getattr(now, str(method))()
except:
pass
输出为:
astimezone combine ctime Mon Apr 24 18:28:12 2017
date 2017-04-24
day: 24
dst None
fromordinal fromtimestamp hour: 18
isocalendar (2017, 17, 1)
isoformat 2017-04-24T18:28:12.514000
isoweekday 1
max: 9999-12-31 23:59:59.999999
microsecond: 514000
min: 0001-01-01 00:00:00
minute: 28
month: 4
now 2017-04-24 18:28:12.515000
replace 2017-04-24 18:28:12.514000
resolution: 0:00:00.000001
second: 12
strftime strptime time 18:28:12.514000
timetuple time.struct_time(tm_year=2017, tm_mon=4, tm_mday=24, tm_hour=18, tm_min=28, tm_sec=12, tm_wday=0, tm_yday=114, tm_isdst=-1)
timetz 18:28:12.514000
today 2017-04-24 18:28:12.516000
toordinal 736443
tzinfo: None
tzname None
utcfromtimestamp utcnow 2017-04-24 10:28:12.516000
utcoffset None
utctimetuple time.struct_time(tm_year=2017, tm_mon=4, tm_mday=24, tm_hour=18, tm_min=28, tm_sec=12, tm_wday=0, tm_yday=114, tm_isdst=0)
weekday 0
year: 2017
判断函数的方法 :
callable(f) #1
import types #2 这个不是太好使,目前还没用对,只是据说这个法子可用
isinstance(fn, types.FunctionType)
hasattr(fn, '__call__') #3