python常見的函數和類方法

在學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函數app

"""
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函數ide

"""
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. 複數類complexspa

"""
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方法code

"""
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函數orm

"""
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
相關文章
相關標籤/搜索