zoukankan      html  css  js  c++  java
  • gj2 python中一切皆对象

    2.1 python中一切皆是对象

        动态语言和静态语言的区别,Python的面向对象更彻底

    同时动态语言,代码的灵活性高

    没有编译(检查)的过程,错误只有在运行起来后才会发现

    函数和类也是对象,属于python的一等公民

          1. 赋值给一个变量

          2. 可以添加到集合对象中

          3. 可以作为参数传递给函数

          4. 可以当做函数的返回值

    def ask(name="lewen"):
        print(name)
    class Persoon(object):
        def __init__(self):
            print("lewen")
    
    obj_list = []
    obj_list.append(ask)
    obj_list.append(Persoon)
    for item in obj_list:
        print(item())
    
    

    lewen
    None
    lewen
    <__main__.Persoon object at 0x0000029B7B3BBA20>

        

    2.2 type、object和class的关系

    type 的用法 1:生成一个类 2:反回一个对象是什么类型

    >>> a = 1
    >>> type(a)
    <class 'int'>
    >>> type(int)
    <class 'type'>
    >>> b = "abc"
    >>> type(b)
    <class 'str'>
    >>> type(str)
    <class 'type'>
    >>> class Student:
    ...     pass
    ...
    >>> stu = Student()
    >>> type(stu)
    <class '__main__.Student'>
    >>> type(Student)
    <class 'type'>

    type->int->1
    type->class->obj

    type是用来生成类的

    >>> type(Student)
    <class 'type'>
    >>> Student.__bases__
    (<class 'object'>,)
    >>> class MyStudent(Student):
    ...     pass
    ...
    >>> MyStudent.__bases__
    (<class '__main__.Student'>,)
    >>> type.__bases__
    (<class 'object'>,)
    >>> type(object)
    <class 'type'>
    >>> object.__bases__
    ()
    >>> type(type)
    <class 'type'>

    # object 是最项层基类
    # type 也是一个类,同时type也是一个对象

    image

    一切都继承自object,一切皆对象

    type 自己是自己的实例(内部通过指针指向同一个内存块)

    2.3 python中的常见内置类型

    对象的三个特征:
    
        身份(对象在内存中的地址)
    
    In [1]: a=1
    In [2]: id(a)
    Out[2]: 140714948027216
        类型(什么类型的对象)
    
        值
    
    None(全局只有一个)
    
    数值:int float complex bool
    
    迭代类型
    
    序列类型
    
        list
         bytes、bytearray、memoryview(二进制序列)
         range
         tuple
         str
         array
    
    映射(dict)
    
    集合:set ,frozenset
    
    上下文管理类型(with)
    
    其他:
       模块类型
       class和实例
       函数类型
       方法类型
       代码类型
       object对象
       type类型
       ellipsis类型
       notimplemented类型
  • 相关阅读:
    MySQL修改root密码的多种方法
    AES和RSA算法的demo代码
    网卡
    Socket
    Opentracing 链路追踪
    TCP连接三次握手
    MongoDB 使用B树
    MySQL的DDL、DML、DCL
    MySQL 数据同步
    SSO(单点登录)与CAS
  • 原文地址:https://www.cnblogs.com/wenyule/p/10357632.html
Copyright © 2011-2022 走看看