本文实例讲述了python自定义类并使用的方法。分享给大家供大家参考。具体如下:
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())
运行结果如下:
raja i kumar 21
raja i kumar 26
rik
希望本文所述对大家的python程序设计有所帮助。