关于类的练习

1. 以下的代码的输出将是什么?
class Parent(object):
x = 1

class Child1(Parent):
pass

class Child2(Parent):
pass

print Parent.x, Child1.x, Child2.x
=========
Parent.x = 1
Child1.x = 1
Child2.x = 1
=========
Ch ild1.x = 2
print Parent.x, Child1.x, Child2.x
=========
Parent.x = 1
Child1.x = 2
Child2.x = 1
=========
Parent.x = 3
print Parent.x, Child1.x, Child2.x
=========
Parent.x = 3
Child1.x = 2
Child2.x = 3

 

 

2. 以下代码将输出什么?
list = ['a', 'b', 'c', 'd', 'e']
print list[10:]
======
[]
======

3. 以下的代码的输出将是什么? 

def extendList(val, list=[]):
list.append(val)
return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
=======
list1 = 10
list2 = [123]
list3 = [123,'a']
=======

4.以下代码将输出什么?

class Node(object):
def __init__(self,sName):
self._lChildren = []
self.sName = sName

def __repr__(self):
return "<Node '{}'>".format(self.sName)

def append(self,*args,**kwargs):
self._lChildren.append(*args,**kwargs)

def print_all_1(self):
print self
for oChild in self._lChildren:
oChild.print_all_1()

def print_all_2(self):
def gen(o):
lAll = [o,]
while lAll:
oNext = lAll.pop(0)
lAll.extend(oNext._lChildren)
yield oNext
for oNode in gen(self):
print oNode

oRoot = Node("root")
oChild1 = Node("child1")
oChild2 = Node("child2")
oChild3 = Node("child3")
oChild4 = Node("child4")
oChild5 = Node("child5")
oChild6 = Node("child6")
oChild7 = Node("child7")
oChild8 = Node("child8")
oChild9 = Node("child9")
oChild10 = Node("child10")

oRoot.append(oChild1)
oRoot.append(oChild2)
oRoot.append(oChild3)
oChild1.append(oChild4)
oChild1.append(oChild5)
oChild2.append(oChild6)
oChild4.append(oChild7)
oChild3.append(oChild8)
oChild3.append(oChild9)
oChild6.append(oChild10)

# 说明下面代码的输出结果

oRoot.print_all_1() 

oRoot.print_all_2() 

==============

oRoot.print_all_1() 的打印结果:

oRoot.print_all_2()的打印结果:

 

 ==============

5.Write a Python class which has two methods get_String and print_String. get_String accept a string from the user and print_String print the string in upper case. 

class GetWords(object):

    def __init__(self):
        self.word = None

    def get_string(self):
        self.word = raw_input("Please enter words:")

    def print_string(self):
        print self.word.upper()


if __name__ == '__main__':
    A = GetWords()
    A.get_string()
    A.print_string()  

 


posted @ 2017-01-07 17:59  prime7  阅读(335)  评论(0编辑  收藏  举报