我开始学习Ruby on Rails的Python。
我想知道是否有办法通过Python Shell查看属于某个类的属性?
在Ruby中,我们只需输入控制台,就可以输入Class的名称,并显示其属性。有没有办法在Python中执行此操作?
Ruby Shell
2.2.0 :001 > User
class User < ActiveRecord::Base {
:id => :integer,
:name => :string,
:email => :string,
:encrypted_password => :string,
:reset_password_token => :string,
:reset_password_sent_at => :datetime,
:remember_created_at => :datetime,
:sign_in_count => :integer,
:current_sign_in_at => :datetime,
:last_sign_in_at => :datetime,
:current_sign_in_ip => :string,
:last_sign_in_ip => :string,
:confirmation_token => :string,
:confirmed_at => :datetime,
:confirmation_sent_at => :datetime,
:unconfirmed_email => :string,
:created_at => :datetime,
:updated_at => :datetime,
:role => :string,
:bio => :text,
:sex => :string,
:title => :string,
:department => :string,
:keywords => :text,
:education => :text,
:skills => :text,
:invitation_token => :string,
:invitation_created_at => :datetime,
:invitation_sent_at => :datetime,
:invitation_accepted_at => :datetime,
:invitation_limit => :integer,
:invited_by_id => :integer,
:invited_by_type => :string,
:invitations_count => :integer
}
2.2.0 :002 >
答案 0 :(得分:1)
使用dir()
功能:
>>> print dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
它适用于任何对象,包括类,内置函数和函数。
如果您希望输出格式更像您的ruby示例:
In [169]: for attrib in dir(str):
print "{0:18} => {1}".format(attrib, type(getattr(str, attrib)))
输出:
__add__ => <type 'wrapper_descriptor'>
__class__ => <type 'type'>
__contains__ => <type 'wrapper_descriptor'>
__delattr__ => <type 'wrapper_descriptor'>
__doc__ => <type 'str'>
__eq__ => <type 'wrapper_descriptor'>
__format__ => <type 'method_descriptor'>
__ge__ => <type 'wrapper_descriptor'>
__getattribute__ => <type 'wrapper_descriptor'>
...
答案 1 :(得分:0)
您实际上不需要打印。你只需使用dir()。