Home > Backend Development > Python Tutorial > python自定义类并使用的方法

python自定义类并使用的方法

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-10 15:13:02
Original
1365 people have browsed it

本文实例讲述了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())
Copy after login

运行结果如下:

Raja I Kumar 21
Raja I Kumar 26
RIK
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template