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程序设计有所帮助。

相关文章

详解如何从TensorFlow的mnist数据集导出手写体数字图片

详解如何从TensorFlow的mnist数据集导出手写体数字图片

在TensorFlow的官方入门课程中,多次用到mnist数据集。 mnist数据集是一个数字手写体图片库,但它的存储格式并非常见的图片格式,所有的图片都集中保存在四个扩展名为idx3-...

Python django使用多进程连接mysql错误的解决方法

Python django使用多进程连接mysql错误的解决方法

问题 mysql 查询出现错误 error: (2014, "Commands out of sync; you can't run this command now")1 查询 m...

python中OrderedDict的使用方法详解

很多人认为python中的字典是无序的,因为它是按照hash来存储的,但是python中有个模块collections(英文,收集、集合),里面自带了一个子类 OrderedDict,实...

Python简单实现安全开关文件的两种方式

本文实例讲述了Python简单实现安全开关文件的两种方式。分享给大家供大家参考,具体如下: 以下代码经Python3.3测试。 方式1: try: file = open('co...

python、PyTorch图像读取与numpy转换实例

Tensor转为numpy np.array(Tensor) numpy转换为Tensor torch.Tensor(numpy.darray) PIL.Image.Image转换成nu...