Python: Generic getters and setters

前端 未结 5 458
天命终不由人
天命终不由人 2021-02-04 06:11

TL;DR: Having to define a unique set of getters and setters for each property()\'d variable sucks. Can I define generic getters and setters and use them with whatever

5条回答
  •  孤街浪徒
    2021-02-04 06:39

    # coding=utf-8
    __author__ = 'Ahmed Şeref GÜNEYSU'
    
    
    class Student(object):
        def __init__(self, **kwargs):
            for k, v in kwargs.iteritems():
                self.__setattr__(k, v)
    
    if __name__ == '__main__':
        o = Student(first_name='Ahmed Şeref', last_name='GÜNEYSU')
        print "{0} {1}".format(o.first_name, o.last_name)
        print o.email
    

    Gives

    Ahmed Şeref GÜNEYSU
      File "/Users/ahmed/PycharmProjects/sanbox/abstract_classes/object_initializer/__init__.py", line 13, in 
        print o.email
    AttributeError: 'Student' object has no attribute 'email'
    
    Process finished with exit code 137
    

提交回复
热议问题