zoukankan      html  css  js  c++  java
  • python常见的函数和类方法

    在学python编程时 常常会遇到些常见的函数 记录学习

    1. getattr函数

    """
    getattr() 函数用于返回一个对象属性值。
    语法:
        getattr(object, name, default)
    参数:
        object -- 对象。
        name -- 字符串,对象属性。
        default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。
    返回值:
        返回对象属性值。
    可用于对象通过类方法名称找到方法
    """
    
    class A(object):
        name = "xxx"
        def func_a(self):
            print("func_a")
    
    a = A()
    getattr(a, "func_a", "default")()   # func_a
    print(getattr(a, "name", "default")) # xxx
    View Code

    2. hasattr函数

    """
    hasattr() 函数用于判断对象是否包含对应的属性。
    语法:
        hasattr(object, name)
    参数:
        object -- 对象。
        name -- 字符串,属性名。
    返回值:
        如果对象有该属性返回 True,否则返回 False。
    用于判断一个对象是否函数属性和方法
    """
    
    class A(object):
        name = "xxx"
        def func_a(self):
            print("func_a")
    
    a = A()
    print(hasattr(a, "name")) # True
    print(hasattr(a, "func_a")) # True
    View Code

    3. delattr函数

    """
    delattr 函数用于删除属性。
    delattr(x, 'foobar') 相等于 del x.foobar。
    语法:
        delattr(object, name)
    参数:
        object -- 对象。
        name -- 必须是对象的属性。
    返回值
        无。
    用于删除对象或者类的某个属性和方法
    """
    
    class A(object):
        a = 10
        b = 100
        c = 1000
    
    a = A()
    print(a.a, a.b, a.c) # 10 100 1000
    delattr(A, "c")
    print(a.a, a.b)  # 10 100
    print(hasattr(a, "c")) # False
    View Code

    4. eval函数

    """
    val()函数用来执行一个字符串表达式,并返回表达式的值。
    返回值:
        返回表达式计算结果。
    用于通过函数名使用函数, 通过字符串进行对应的操作, 实现list、dict、tuple与str之间的转化
    """
    
    class A(object):
        name = "xxx"
        def func_a(self):
            print("func_a")
    
    a = A()
    print(eval("a.name"))  # xxx
    eval("a.func_a()")   # func_a
    
    x = 100
    print(eval("3 * x"), type(eval("3 * x")))  # 300 <class 'int'>
    
    str1 = "[1, 2, 3, 4, 5]"
    list1 = eval(str1)
    print(list1, type(list1))  # [1, 2, 3, 4, 5] <class 'list'>
    View Code

    5. extend方法

    """
    list.extend函数是列表下的一个函数,可以合并一个列表
    语法:
        list.extend(seq)
    参数:
        seq为元素列表
    返回值:
        无
    用于合并一个列表 区别与list.append函数
    """
    a = [1, 2, 3]
    b = [7, 8, 9]
    a.extend(b)
    print(a)  # [1, 2, 3, 7, 8, 9]
    a = [1, 2, 3]
    b = [7, 8, 9]
    a.append(b)
    print(a)  # [1, 2, 3, [7, 8, 9]]
    View Code

    6. 复数类complex

    """
    complex类用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。
    语法:
        class complex([real[, imag]])
    参数:
        real -- int,long,float或字符串
        imag -- int,long,float
    返回值:
        返回complex对象
    """
    
    x = complex(1)
    print(x, type(x)) # 1+0j) <class 'complex'>
    print(complex(1, 2))  # (1+2j)
    print(complex("1+2j")) # (1+2j)
    # print(complex("1 +2j")) # 报错 不能出现空格
    # print(complex("1+2j", 2)) # 报错 当第一个参数为字符串时 第二个参数不能有值
    View Code

    7. join方法

    """
    Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
    语法:
        str.join(sequence)
    参数:
        sequence -- 要连接的元素序列、字符串、元组、字典
    返回值:
        返回通过指定字符连接序列中元素后生成的新字符串。
    """
    
    list1 = ["1", "2", "3"]
    x = "---".join(list1)
    print("---".join(list1), type(x)) # 1---2---3 <class 'str'>
    dict1 = {"a":1, "b":2, "c":3}
    print("---".join(dict1))
    View Code

    8. isinstance函数

    """
    isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。
    语法:
        isinstance(object, classinfo)
    参数:
        object -- 实例对象。
        classinfo -- 可以是直接或间接类名、基本类型或者由它们组成的元组。
    返回值:
        如果对象的类型与参数二的类型(classinfo)相同则返回 True,否则返回 False。。
    isinstance() 与 type() 区别:
        type() 不会认为子类是一种父类类型,不考虑继承关系。
        isinstance() 会认为子类是一种父类类型,考虑继承关系。
        如果要判断两个类型是否相同推荐使用 isinstance()。
    """
    
    x = "str1"
    print(isinstance(x, str))  # True
    print(isinstance(x, (str, int, bool))) # True
    
    
    class A:
        pass
    class B(A):
        pass
    a = A()
    b = B()
    print(isinstance(a, A))  #  True
    print(type(a) == A ) #  True
    print(isinstance(b, A))  #  True
    print(type(b) == A)  #  False
    View Code

    9. format函数

    """
    format格式化函数
    语法:
        format(*arg:**kwarg)
    参数:
        :冒号前面为参数所对应的位置
        :冒号后面为数字格式化
    返回值:
        返回格式化后的字符串
    用于字符串格式化
    """
    
    print("{} {}".format("hello", "world") )   # hello world
    print("{1} {0} {1}".format("hello", "world") )   # world hello world
    
    print("name:{name}, age :{age}".format(name="jack", age=18)) # name:jack, age :18
    dict1 = {"name":"jack", "age":18}
    print("{name} is {age}".format(**dict1))  # jack is 18
    list1 = ["jack", 18]
    print("{0[0]} is {0[1]}".format(list1)) # jack is 18
    
    class Person(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age
    p = Person("jack", 18)
    print("{0.name} is {0.age}".format(p))  # jack is 18
    
    
    name = "jack"
    print('{0:.3}'.format(1/3))  # 精确位数   0.333
    print('{0:_^11} is a 11 length. '.format(name)) # 使用_补齐空位  ___jack____ is a 11 length.
    print('My name is {0.name}'.format(open('out.txt', 'w'))) # 调用方法  My name is out.txt
    print('My name is {:15} ok.'.format('Fred')) # 指定宽度    My name is Fred
    print("{0:,}".format(100000000000))   # 100,000,000,000
    print('{:4}'.format(11))    #  占用4个位置 11
    View Code
  • 相关阅读:
    mysql数据引擎
    R语言入门
    springboot整合springmvc、mybatis
    svn搭建和配置
    UML常用图的几种关系的总结
    cookies和session机制
    Java总结篇系列:Java多线程(三)
    Java总结篇系列:Java多线程(一)
    Java总结篇系列:Java多线程(二)
    restframework之认证
  • 原文地址:https://www.cnblogs.com/KIV-Y/p/10699202.html
Copyright © 2011-2022 走看看