>>> class pp: ... pass ... >>> p = pp() >>> print p <__main__.pp instance at 0x00CA77B0> >>>
>>> class Person:
... def __init__(self, name):
... self.name = name
... def sayHi(self):
... print 'Hello, my name is', self.name
...
>>> p = Person('Swaroop')
>>> p.sayHi()
Hello, my name is Swaroop
>>>
>>> class Person:
... population = 0
... def __init__(self, name):
... self.name = name
... print '(Initializing %s)' % self.name
... def __del__(self):
... print '%s says bye.' % self.name
... Person.population -= 1
...
... def howMany(self):
... if Person.population == 1:
... print 'I am the only person here.'
... else:
... print 'We have %d persons here.' % Person.population
...
>>> A = Person('aa')
(Initializing aa)
>>> A.howMany()
We have 0 persons here.
>>> B = Person('bb')
(Initializing bb)
>>> B.howMany()
We have 0 persons here.
>>> ^Z
aa says bye.
bb says bye.
class CAnimal:
name = 'unname'
# 成员变量
def __init__(self,voice='hello'):
# 重载构造函数
self.voice = voice
# 创建成员变量并赋初始值
def __del__(self):
# 重载析构函数
pass # 空操作
def Say(self):
print self.voice
t = CAnimal() # 定义动物对象t
t.Say() # t说话
>> hello # 输出
dog = CAnimal('wow') # 定义动物对象dog
dog.Say() # dog说话
>> wow # 输出
class CAnimal:
def __init__(self,voice='hello'):
# voice初始化默认为hello
self.voice = voice
def Say(self):
print self.voice
def Run(self):
pass # 空操作语句(不做任何操作)
class CDog(CAnimal): # 继承类CAnimal
def SetVoice(self,voice): # 子类增加函数
SetVoice self.voice = voice
def Run(self,voice): # 子类重载函数Run
print 'Running'
bobo = CDog()
bobo.SetVoice('My Name is BoBo!')
# 设置child.data为hello
bobo.Say()
bobo.Run()
>> My Name is BoBo!
>> Running
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有