Python之路

Python 类和类实例

2017-09-19  本文已影响4人  陈宝佳
>>> class FooClass(object):
...     """my very first class: FooClass"""
...     version = 0.1
...     def __init__(self, nm='Chenbaojia'):
...             """constructor"""
...             self.name = nm
...             print 'Created a class instance for', nm
...     def showname(self):
...             """display instance attribute and class name"""
...             print 'Your name is', self.name
...             print 'My name is', self.__class__.__name__
...     def showver(self):
...             """display class(static) attribute"""
...             print self.version
...     def addMe2Me(self,x):
...             """apply + operation to argument"""
...             return x + x
... 
>>> foo1 = FooClass()
Created a class instance for Chenbaojia
>>> FooClass()
Created a class instance for Chenbaojia
<__main__.FooClass object at 0x102abcc50>
>>> foo1.showname()
Your name is Chenbaojia
My name is FooClass
>>> FooClass().showname()
Created a class instance for Chenbaojia
Your name is Chenbaojia
My name is FooClass
>>> foo1.showver()
0.1
>>> FooClass().showver()
Created a class instance for Chenbaojia
0.1
>>> FooClass.showver()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method showver() must be called with FooClass instance as first argument (got nothing instead)
>>> print foo1.addMe2Me(5)
10
>>> print FooClass().addMe2Me(5)
Created a class instance for Chenbaojia
10
>>> print foo1.addMe2Me('xyz')
xyzxyz
>>> print FooClass().addMe2Me('xyz')
Created a class instance for Chenbaojia
xyzxyz
>>> foo2 = FooClass('Jane Smith')
Created a class instance for Jane Smith
>>> foo2.showname()
Your name is Jane Smith
My name is FooClass
>>> 

上一篇 下一篇

猜你喜欢

热点阅读