【发布时间】:2021-07-20 03:20:05
【问题描述】:
class User():
def __init__(self, first, last, location, gender):
self.first = first
self.last = last
self.location = location
self.gender = gender
self.loginattempt = 0
def mmplusattempt(self):
self.loginattempt += 1
def mmresetattempt(self):
self.loginattempt = 0
def mmdescribe(self):
attributes = [a for a in dir(self) if not a.startswith(('__', 'mm'))]
for att in attributes:
print(att + ": " + str(getattr(self, att)))
new = User('david', 'johnson', 'usa', 'male')
new.mmdescribe()
输出:
└─$ python3 classuser.py
first: david
gender: male
last: johnson
location: usa
loginattempt: 0
问题是,或者 attributes = [a for a in dir(self) if not a.startswith('__')] 正在返回所有属性,包括我不想要的 plusattempt resetattempt describe。我不想打印任何方法,所以我想也许我可以让所有方法名称以mm 开头并使用a.startswith(('__', 'mm'))] 过滤掉它们。现在这绝对有效,但我觉得必须有一个我现在想不出的更好的方法。另外,如果有我不想打印的属性(不是方法),我将不得不在名称中添加mm,这不是很有效。
- 如何打印
new的属性(不包括方法)? (除了我展示的方式)我相信还有一种更优雅的方式来写这个。
【问题讨论】:
-
也许this 会有所帮助。
标签: python python-3.x attributes getattr