python构造函数调用成员函数_python面向对象入门实例(构造函数、方法调用)

例1: 代码示例:

#!/usr/bin/python

# Filename: simplestclass.py

class Person:

pass # An empty block

p = Person()

print p

$ python simplestclass.py

例2: 代码示例:

#!/usr/bin/python

# Filename: method.py

class Person:

def sayHi(self):

print 'Hello, how are you?'

p = Person()

p.sayHi()

# This short example can also be written as Person().sayHi()

$ python method.py

Hello, how are you?

-------__init__----------是不是可以称为构造方法

例3: 代码示例:

#!/usr/bin/python

# Filename: class_init.py

class Person:

def __init__(self, name):

self.name = name

def sayHi(self):

print 'Hello, my name is', self.name

p = Person('Swaroop')

p.sayHi()

# This short example can also be written as Person('Swaroop').sayHi()

$ python class_init.py

Hello, my name is Swaroop

例4: 代码示例:

#!/usr/bin/python

# Filename: objvar.py

class Person:

'''Represents a person.'''

population = 0

def __init__(self, name):

'''Initializes the person's data.'''

self.name = name

print '(Initializing %s)' % self.name

# When this person is created, he/she

# adds to the population

Person.population += 1

def __del__(self):

'''I am dying.'''

print '%s says bye.' % self.name

Person.population -= 1

if Person.population == 0:

print 'I am the last one.'

else:

print 'There are still %d people left.' % Person.population

def sayHi(self):

'''Greeting by the person.

Really, that's all it does.'''

print 'Hi, my name is %s.' % self.name

def howMany(self):

'''Prints the current population.'''

if Person.population == 1:

print 'I am the only person here.'

else:

print 'We have %d persons here.' % Person.population

swaroop = Person('Swaroop')

swaroop.sayHi()

swaroop.howMany()

kalam = Person('Abdul Kalam')

kalam.sayHi()

kalam.howMany()

swaroop.sayHi()

swaroop.howMany()

$ python objvar.py

(Initializing Swaroop)

Hi, my name is Swaroop.

I am the only person here.

(Initializing Abdul Kalam)

Hi, my name is Abdul Kalam.

We have 2 persons here.

Hi, my name is Swaroop.

We have 2 persons here.

Abdul Kalam says bye.

There are still 1 people left.

Swaroop says bye.

I am the last one.

当对象不再被使用时,__del__方法运行。

如果要指明它的运行,需要使用del语句。

例子很简单,作为python面向对象的入门学习参考还可以。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值