python基础学习-类(class)

来源:互联网 发布:js的object对象 编辑:程序博客网 时间:2024/06/05 09:25

python类的基本用法

ython 2.7.13 (default, Jan 19 2017, 14:48:08) 

[GCC 6.3.0 20170118] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> class People:
age = 0
name = ""
sex = True
def __init__(self,age=21,name="xiaobing",sex=True):
self.age = age
self.name = name
self.sex = sex



>>> p = People()
>>> p
<__main__.People instance at 0x7facc0766680>
>>> p.age
21
>>> p.name
'xiaobing'
>>> p.sex
True
>>> p = People(22,"xiaohong",False)
>>> p.age
22
>>> p.name
'xiaohong'
>>> p.sex
False
>>> del People
>>> class People:
def say(self,something="nothing"):
print "say"+str(something)



>>> del p
>>> p = People()
>>> p.say("hello world)
      
SyntaxError: EOL while scanning string literal
>>> p.say("hello world")
sayhello world
>>> p.say()

saynothing



python类的成员访问权限问题

Python 2.7.13 (default, Jan 19 2017, 14:48:08) 
[GCC 6.3.0 20170118] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> class Test:
def __test(self):
print "test"



>>> t = Test()
>>> t._Test__test
<bound method Test.__test of <__main__.Test instance at 0x7f613cb1a248>>
>>> t.test()


Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    t.test()
AttributeError: Test instance has no attribute 'test'


>>> class Test:
def __init__(self):
self.__t = 0
self.tt = 0
def _test(self):
print self.tt
def setT(self,t):
self.__t = t
def getT(self):
return self.__t



>>> test = Test()
>>> test.tt
0
>>> test._t


Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    test._t
AttributeError: Test instance has no attribute '_t'
>>> test.t


Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    test.t
AttributeError: Test instance has no attribute 't'
>>> test.get


Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    test.get
AttributeError: Test instance has no attribute 'get'
>>> test.getT()
0
>>> test.setT(10)
>>> test.getT()
10


python的静态成员属性和静态成员方法

>>> class Test:
t = 0
@staticmethod
def test():
print "test"



>>> Test.t
0
>>> Test.test()
test
>>> 



python类的继承

>>> class MyList(list):
def myPrint(self):
for item in self:
print item



>>> mList = MyList()
>>> mList.myPrint()
>>> mList.append(1)
>>> mList.myPrint()
1
>>> mList = mList + [1,2,3,4]
>>> mList
[1, 1, 2, 3, 4]