python自定义类并使用的方法

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

python实现sublime3的less编译插件示例

利用http://tool.oschina.net/less 提供的接口,发送请求进行远程编译.再将编译好的less,保存为同名后缀为css的文件中.第一次使用python,代码也是拼拼...

对pandas replace函数的使用方法小结

对pandas replace函数的使用方法小结

语法:replace(self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method=...

python自动化工具日志查询分析脚本代码实现

受控节点slave.py 复制代码 代码如下:import socketimport reclass Log(object):    file_list=[...

python itchat给指定联系人发消息的方法

itchat模块 官方参考文档:https://itchat.readthedocs.io/zh/latest/ 安装 pip install itchat / pip3 insta...

python多线程http下载实现示例

测试平台 Ubuntu 13.04 X86_64 Python 2.7.4 花了将近两个小时, 问题主要刚开始没有想到传一个文件对象到线程里面去, 导致下载下来的文件和源文件MD5不一样...