對象 get set方法生成
if __name__ == '__main__':
# Country 是你自己定義的類
obj = Country()
print(obj.__dict__)
for k in obj.__dict__:
print("def set_" + k + "(self," + k + "):")
print("\tself." + k, "=" + k)
print("def get_" + k + "(self):")
print("\treturn self." + k)
自定義對象打印所有屬性
def obj_to_string(cls, obj):
"""
簡單地實現(xiàn)類似對象打印的方法
:param cls: 對應(yīng)的類(如果是繼承的類也沒有關(guān)系,比如A(object), cls參數(shù)傳object一樣適用,如果你不想這樣,可以修改第一個if)
:param obj: 對應(yīng)類的實例
:return: 實例對象的to_string
"""
if not isinstance(obj, cls):
raise TypeError("obj_to_string func: 'the object is not an instance of the specify class.'")
to_string = str(cls.__name__) + "("
items = obj.__dict__
n = 0
for k in items:
if k.startswith("_"):
continue
to_string = to_string + str(k) + "=" + str(items[k]) + ","
n += 1
if n == 0:
to_string += str(cls.__name__).lower() + ": 'Instantiated objects have no property values'"
return to_string.rstrip(",") + ")"
使用方法 在自定義對象中 添加 下列方法 之后 直接print(obj) 即可打印
def __str__(self):
return obj_to_string(Country, self)