zoukankan      html  css  js  c++  java
  • python类定义

    在我的收藏中有一篇特别详细的类讲解

     此处部分内容引自:http://blog.sina.com.cn/s/blog_59b6af690101bfem.html

    class myclass:
    'this is my first class of python'

    # foo是类属性,相当于static foo是静态成员,可以用类名直接访问
    foo=100

    # myfun 是类方法,必须由类的实例来调用
    def myfun (self):
    print myclass.foo
    C=myclass()
    C.myfun()


    类的特殊属性

    myclass 是类定义

    print myclass.__name__ output:myclass貌似只有类定义有这个属性,类实例没有这个属性
    print myclass.__doc__ output:'this is my first class of python' 类的文档字符串
    print myclass.__dict__ output:类的所有属性和方法,只有类定义有,实例这个属性输出空
    print myclass.__module__ output:__main__类定义所在的模块

    C是类的实例

    print C.__doc__ output:'this is my first class of python' 类的文档字符串,实例也有此属性
    print C.__dict__ output:{} 实例没有这个属性,输出为空
    print C.__module__ output:__main__ 类定义所在的模块
    print C.__class__ output: myclass 实例对应的类名,仅实例有此属性

    类的构造

    class myclass:
    'this is my first class of python'
    foo=100
    def myfun (self):
    print "class's func "

    def __init__(self,msg='hello'):
    self.msglist=msg //实例属性可以动态的添加,此时是在构造时候添加完成
    print 'init'

    print myclass.foo
    C=myclass()
    C.myfun()
    print C.msglist

     

    注意,python可以灵活的随时为类或是其实例添加类成员,有点变态,而且实例自身添加的成员,与类定义无关:

    //添加一个类实例的成员

    C.name='genghao'

    现在实例C有了数据成员 name

    现在加入这两句

    print C.__dict__
    print myclass.__dict__

    可以看到类定义里面并没有添加成员name,说明它仅仅属于类的实例C

    类继承:

    class subclass(myclass):

             member='sdkfjq'

             def  func(self):

                    print "sdfa"

    多重继承:

    class multiple_inheritance(myclass,subclass,ortherclass):

                 def funy():

                          do what you want to do
     

    测试代码:

    class ttt:
        name= 42
      
        def __init__(self,voice='hello'):
            self.voice=voice#new member for class
        def member(self):
            self.name=63
            self.strane='st' #new member for class
        def say(self):
            print self.voice

    t= ttt()
    t.say()
    print t.name

    t.member()
    t.fuc='sdfa'#new member for instance of the class ttt
    print t.name

    print ttt.__name__

    print ttt.__dict__
    print t.__dict__
    print t.fuc

  • 相关阅读:
    1024X768大图 (Wallpaper)
    (Mike Lynch)Application of linear weight neural networks to recognition of hand print characters
    瞬间模糊搜索1000万基本句型的语言算法
    单核与双核的竞争 INTEL P4 670对抗820
    FlashFTP工具的自动缓存服务器目录的功能
    LDAP over SSL (LDAPS) Certificate
    Restart the domain controller in Directory Services Restore Mode Remotely
    How do I install Active Directory on my Windows Server 2003 server?
    指针与指针变量(转)
    How to enable LDAP over SSL with a thirdparty certification authority
  • 原文地址:https://www.cnblogs.com/cl1024cl/p/6205648.html
Copyright © 2011-2022 走看看