python获取对象信息(python基础学习)

dir()函数可以返回变量的所有属性,返回的属性是字符串列表

>>> list =[]
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

如果已知一个属性名称,要获取或者设置对象的属性,需要用 getattr()  setattr( )函数

class Person(object):

    def __init__(self, name, gender, **kw):
        self.name = name
        self.gender = gender
        for key,value in kw.items():
            setattr(self,key,value)

p = Person('Bob', 'Male', age=18, course='Python')
print p.age
print p.course

你可能感兴趣的:(python语言)