• Python学习笔记之五:类定义


    这里,我定义了一个类,初始化函数,Show函数,并且定义了文档字符串,使用了help函数和__doc__来调用文档字符串

    >>> class FooClass(object):
        "This is my first class !"
        def __init__(self, name="NoName"):
            "This is a kinda construct funtion."
            self.name = name
        def show(self):
            "This is a print function."
            print 'My name is', self.name
    
            
    >>> fc = FooClass('Tiejiaxiaobao')
    >>> fc.show()
    My name is Tiejiaxiaobao
    >>> help(FooClass)
    Help on class FooClass in module __main__:
    
    class FooClass(__builtin__.object)
     |  This is my first class !
     |  
     |  Methods defined here:
     |  
     |  __init__(self, name='NoName')
     |      This is a kinda construct funtion.
     |  
     |  show(self)
     |      This is a print function.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    >>> help(FooClass.show)
    Help on method show in module __main__:
    
    show(self) unbound __main__.FooClass method
        This is a print function.
    
    >>> FooClass.__doc__
    'This is my first class !'
    >>> FooClass.show.__doc__
    'This is a print function.'
    >>> 

     这里,我分别测试了几种类成员变量的声明方式,试图发现关于变量定义的规律

    >>> class FooClass(object):
        #members list
        name = 'NoName'
        name1 = 'NoName1'
        name2 = 'NoName2'
        def __init__(self, name):
            self.name = name
        def func1(self):
            self.name1 = self.name
            print self.name1
        def func2(self):
            self.name2 = self.name1
            print self.name2
    
            
    >>> obj = FooClass('Tie Jia Xiao Bao')
    >>> obj.name2
    'NoName2'
    >>> obj.func2()
    NoName1
    >>> obj.func1()
    Tie Jia Xiao Bao
    >>> obj.func2()
    Tie Jia Xiao Bao
    >>> obj.__dict__
    {'name2': 'Tie Jia Xiao Bao', 'name': 'Tie Jia Xiao Bao', 'name1': 'Tie Jia Xiao Bao'}
    >>> obj = FooClass('Tie')
    >>> obj.__dict__
    {'name': 'Tie'}
    >>> obj.func2()
    NoName1
    >>> obj.__dict__
    {'name2': 'NoName1', 'name': 'Tie'}
    >>> obj.name1
    'NoName1'
    >>> obj.__dict__
    {'name2': 'NoName1', 'name': 'Tie'}
    >>> obj.func1()
    Tie
    >>> obj.__dict__
    {'name2': 'NoName1', 'name': 'Tie', 'name1': 'Tie'}
    >>> 
  • 相关阅读:
    vue移动框架vonic
    vue桌面端框架element
    vuex最简单的入门文档
    Vuex最简单教程
    环境配置
    【转】MyEclipse8.5集成Tomcat7时的启动错误:Exception in thread “main” java.lang.NoClassDefFoundError org/apache/commons/logging/LogFactory
    Java中获取完整的url
    【转载】Android Studio 设置内存大小及原理
    Android上实现仿IOS弹性ScrollView
    ServletContextListener 启动SPRING加载数据到缓存的应用
  • 原文地址:https://www.cnblogs.com/zanzan101/p/3647331.html
Copyright © 2020-2023  润新知