zoukankan      html  css  js  c++  java
  • Python 类机制

    >>> class MyData(object): //类作为名称空间容器
    ... pass
    ...
    >>> mathObj = MyData()
    >>> mathObj.x=4
    >>> mathObj.y=5
    >>> mathObj.x+mathObj.y
    9
    >>>
    >>> mathObj.x*mathObj.y
    20

    self(实例对象)参数自动由解释器传递

    类中方法只能通过实例来调用
    类中静态变量可以直接使用

    实例仅拥有数据属性

    在类属性可变的情况下

    >>> class Foo(object):
    ... x = {2003:'poe2'}
    ...
    >>> foo = Foo()
    >>> foo.x
    {2003: 'poe2'}
    >>> foo.x[2004] = 'valid path'
    >>> foo.x
    {2003: 'poe2', 2004: 'valid path'}
    >>> Foo.x
    {2003: 'poe2', 2004: 'valid path'}
    >>> del foo.x
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AttributeError: 'Foo' object attribute 'x' is read-only

    绑定方法与非绑定方法
    非绑定方法:主要场景是在派生一个子类,而且要覆盖父类的方法,需要调用这个父类中想要覆盖的构造方法
    http://blog.sina.com.cn/s/blog_3fe961ae0100kew0.html
    http://cowboy.1988.blog.163.com/blog/static/75105798201091141521583/

    >>> class TestMethod:
    ... def func():
    ... print "hehe"
    ...
    >>> test_method = TestMethod()
    >>> test_method.func()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: func() takes no arguments (1 given)


    >>> class TestStaticMethod:
    ... def foo():
    ... print 'calling static method foo()'
    ... foo = staticmethod(foo)
    ...
    >>> class TestClassMethod:
    ... def foo(cls):
    ... print 'calling class method foo()'
    ... print 'foo() is part of class:',cls.__name__
    ... foo = classmethod(foo)
    ...
    >>>
    >>>
    >>>
    >>> Test_foo = TestStaticMethod()
    >>> Test_foo.foo()
    calling static method foo()
  • 相关阅读:
    express中 使用session与cookie
    mongoDB
    原生 js 实现 vue 的某些功能
    linux系统
    nodejs 程序(有的功能和前端js是不一样的)
    内网穿透技术
    webview
    PWA 应用
    计算机 和 互联网 知识
    css 图片 和 文本 的处理
  • 原文地址:https://www.cnblogs.com/moonflow/p/2394683.html
Copyright © 2011-2022 走看看