这篇文章主要介绍了Python自定义类并使用的方法,涉及Python中类的定义与使用技巧,需要的朋友可以参考下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Person: def __init__(self, first, middle, last, age): self.first = first; self.middle = middle; self.last = last; self.age = age; def __str__(self): return self.first + ' ' + self.middle + ' ' + self.last + ' ' + str(self.age) def initials(self): return self.first[0] + self.middle[0] + self.last[0] def changeAge(self, val): self.age += val myPerson = Person('Raja', 'I', 'Kumar', 21) print(myPerson) myPerson.changeAge(5) print(myPerson) print(myPerson.initials()) |
运行结果如下: ?
1 2 3 | Raja I Kumar 21 Raja I Kumar 26 RIK |