美文网首页Python之路
Python 类和类实例

Python 类和类实例

作者: 陈宝佳 | 来源:发表于2017-09-19 11:04 被阅读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
    >>> 
    
    

    相关文章

      网友评论

        本文标题:Python 类和类实例

        本文链接:https://www.haomeiwen.com/subject/fzlwsxtx.html