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的常用矩阵生成方式

我就废话不多说了,直接上代码吧! #全0和全1矩阵 v1 = tf.Variable(tf.zeros([3,3,3]), name="v1") v2 = tf.Variabl...

python中join()方法介绍

描述 Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。 语法 join()方法语法: str . join ( sequence ) 参数 sequ...

python调用c++ ctype list传数组或者返回数组的方法

示例1: pycallclass.cpp: #include <iostream> using namespace std; typedef unsigned char...

django中forms组件的使用与注意

forms组件 django框架提供了一个Form类,来进行web开发中的表单提交数据的处理工作。 导入相关模块 from django import forms from dja...

python转换摩斯密码示例

复制代码 代码如下:CODE = {'A': '.-',     'B': '-...',   'C': '-.-.',&nb...