python类和对象Word下载.docx
《python类和对象Word下载.docx》由会员分享,可在线阅读,更多相关《python类和对象Word下载.docx(8页珍藏版)》请在冰豆网上搜索。
people.name
'
people.p
Traceback(mostrecentcalllast):
File"
<
pyshell#7>
"
line1,in<
module>
AttributeError:
classpeoplehasnoattribute'
p'
people.printName()
pyshell#8>
TypeError:
unboundmethodprintName()mustbecalledwithpeopleinstanceasfirstargument(gotnothinginstead)
people.printName(self)
pyshell#9>
NameError:
name'
self'
isnotdefined
p=people()
p.name
p.age
20
p.printName()
jim
classpeople1:
__name='
mike'
__age=20
sex='
wemom'
p1=people1()
p1.__name
pyshell#20>
people1instancehasnoattribute'
__name'
p1.__age
pyshell#21>
__age'
p1.sex
类的内置函数
classc1:
deftell(self):
print"
thisisaclass"
def__init__(self):
c1isinit"
def__del__(self):
c1isdel"
c11=c1()
c1isinit
c11=0
c1isdel
三、类属性、实例属性、类方法、实例方法、静态方法
alice'
__age=13
p.__age
pyshell#41>
peopleinstancehasnoattribute'
实例对象可以调用类里面定义的公有属性,不能调用私有属性。
people.__age
pyshell#43>
类对象可以调用类里面定义的公有属性,不能调用私有属性。
p.sex='
man'
#sex是实例属性
people.sex
pyshell#46>
sex'
实例属性不能被类对象调用
p2=people()
p2.sex
pyshell#49>
实例属性不能被其他实例对象调用
p.sex
实例属性只能被定义该属性的实例对象调用
country='
china'
@classmethod#声明为类方法
defgetCountry(cls):
returncls.country
people.getCountry()
类方法可以被类对象调用
p.getCountry()
类方法可以被实例对象调用
@classmethod
defsetCountry(cls,a):
#使用类方法修改类属性
cls.country=a
returna
p.setCountry('
a'
)
people.setCountry('
b'
defgetCountry(self):
#实例属性
returnself.country
pyshell#87>
unboundmethodgetCountry()mustbecalledwithpeopleinstanceasfirstargument(gotnothinginstead)
实例方法不能被类对象访问
实例方法可以被实例对象访问
@staticmethod#声明为静态方法,静态方法不需要参数
defgetCountry():
returnpeople.country
printpeople.getCountry()
China
静态方法可以被类对象访问
p=people()
静态方法也可以被实例对象访问
四、继承
单继承:
classstudent:
name="
aa"
age=13
self.name="
bb"
self.grade="
high"
self.__sex="
man"
print"
initing"
def__del(self):
dead"
defeat(self):
iameating"
@staticmethod
defrunSelf():
instaticmethod"
def__hello(self):
hello"
classminiStudent(student):
pass
mini=miniStudent()
printmini.__hello()
多继承:
classstudentA:
initstudentA"
defsmile(self):
smile"
age=12
self.addr="
shanghai"
initstudent"
classminiStudent(studentA,student):
studentA.__init__(self)
student.__init__(self)
printmini.addr