python 中 __init__的用法和含义

python 中 __init__  与PHP中的构造函数相似__construct() 

都具有初始化的作用。

1.python中的__init__是一个私有函数(方法),访问私有函数中的变量在python中用self,在PHP中用$this

2.在python类的定义中,一个函数(php叫方法)的参数中必须带有self参数,且self放在第一位

如下例子

class person():

def __init__(self,name,gender,birth,**kw)://可使用 **kw定义关键参数,代表任意参数 ,python中函数的代码块用:php用;

  self.name=name  

  self.gender=gender

  self.birth=birth

  for k,w in kw.iteritems():

    setattr(self,k,w)    //python中是按照缩进来判断代码块的从属

def sayhi(self):

   print 'my name is',self.name

xiaoming = person('Xiao Ming', 'Male', '1991-1-1',job='student',tel='18089355',stdid='15010')  //php中实例类用new,

xiaohong = person('Xiao Hong', 'Female', '1992-2-2') 

print xiaoming.name

print xiaohong.birth

print xiaoming.job

print xiaoming.tel

print xiaoming.stdid

print xiaoming.sayhi()

---------------------------------------

运行结果如下

Xiao Ming

1992-2-2

student

18089355

15010

my name is Xiao Ming

 

 

posted @ 2017-03-21 10:42  在下刘彦直  阅读(1156)  评论(0编辑  收藏  举报