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

  • 相关阅读:
    [Luogu P3626] [APIO2009] 会议中心
    杭电 1869 六度分离 (求每两个节点间的距离)
    杭电 1874 畅通工程续 (求某节点到某节点的最短路径)
    最短路径模板
    杭电 2544 最短路径
    POJ 1287 Networking (最小生成树模板题)
    NYOJ 1875 畅通工程再续 (无节点间距离求最小生成树)
    POJ 2485 Highways (求最小生成树中最大的边)
    杭电 1233 还是畅通工程 (最小生成树)
    杭电 1863 畅通工程 (最小生成树)
  • 原文地址:https://www.cnblogs.com/cl1024cl/p/6205648.html
Copyright © 2011-2022 走看看