Python: Built-in Functions ที่ควรรู้
Built-in Functions คือ function ที่เรียกใช้งานได้เลยโดยที่ไม่ต้องสร้างขึ้นมาเองมีทั้งหมด 69 functions ตามตารางด้านล่างนะคับ
สำหรับ String method ติดตามได้ที่นี่เลยครับ => medium
แต่ใน Article นี้จะทดสอบ functions ที่คุ้นเคยดังต่อไปนี้นะคับ
1.all()
2. any()
3. ascii()
4. ord()
5. chr()
6. bin()
7. bool()
8. breakpoint()
9. bytes()
10. bytearray()
11. callable()
12. classmethod()
13. compile()
14. complex()
15. delattr()
16. dict()
17. dir()
18. divmod()
19. enumerate()
20. eval()
21. exec()
22. filter()
23. float()
24. format()
25. map()
26. open()
27. next()
28. reversed()
29. vars()
30. zip()
31. print()
32. min()
33. max()
34. abs()
35. round()
36. pow()
37. hasattr() : ไว้สำหรับเช็คว่า ในคลาสมี method นี้รึป่าว.
38. set() : มีคุณสมบัติของ distinct คือ ไม่แสดงข้อมูลที่ซ้ำกัน
39. isinstance(): เอาไว้เช็ค type หรือ class ว่าเป็น type นั้นๆไหม
40. rstrip() : ใช้สำหรับ remove last charactor หรือ ด้านขวานั่นแหละ โดยระบุ character ด้านในได้เลย
เราลองหยิบหยกมาใช้งานกันให้เห็นภาพดูนะคับ
- all(iterable)
เป็น function สำหรับตรวจสอบ True, False ของกลุ่มข้อมูล ถ้าในกลุ่มมีข้อมูลที่เป็น False แม้แต่ตัวเดียวจะ return True ทันทีเช่น
วิธีจำง่ายๆนะคับ แค่จำว่า ทุก elements ต้องเป็น True หมดนั่นเอง
>>> all([1,0,1])
False # เพราะมี 0 อยู่ใน list ด้วยจึง return "False"
>>> all([1,1,1])
True>>> all(map(lambda x:x%2==0, range(-5,13,4)))
False # เป็นการตรวจสอบว่าเป็นเลขคู่หมดไหม ซึ่งไม่หมดเลยเป็น False
>>> all(map(lambda x:x%2==0, range(-4,13,4)))
True # ตรวจสอบแล้วเป็นเลขคู่ทั้งหมดจ้า
2. any(iterable)
any จะต่างจาก all ตรงที่ถ้าในกลุ่มข้อมูล iterable มีตัวไหนที่มีค่าเป็น True แค่ตัวเดียวเท่านั้น ก้อจะ return True ออกมาจาก function เลย เช่น
>>> any([1,0,1])
True
>>> any([0,0,0])
False # แบบนี้คือ ไม่มีตัวไหนเป็น 1 หรือเป็น True เลย>>> any(map(lambda x:x>0,[-7,-1,2,-5]))
True # เพราะมี 2 ซึ่งมากกว่า 0 แค่ตัวเดียวก้อ return True เลย
>>> any(map(lambda x:x>0,[-7,-1,0,-5]))
False
หรือ ผมอยากลอง apply เพื่อหาว่าใน List มี element ที่ชื่อ ‘start_date
’, ‘end_date
’ บ้างไหม
data = [
1,
'end_date',
3,
4,
5
]
has_data = any(key in data for key in ['start_date', 'end_date'])
print(has_data)
# Output: True
หรือจะเช็ค key ที่อยู่ใน dict ก็ได้เช่นกัน
data = {
'start_date': 'love',
'q': 'pig'
}
result = any(key in data.keys() for key in ['start_date', 'end_date'])
print(result)
# Output: True
หรือในเคสนี้จะเป็นการประยุกต์ใช้ร่วมกับ not จึงมีความหมายว่า
“ถ้าไม่มีอันใดอันหนึ่งเลย” ก้อจะ raise Error
ออกไปนะ
- ถ้าใช้แค่
any()
หมายความว่า ถ้ามีTrue
แค่ตัวเดียว ก้อจะทำเลย จำง่ายๆเลยว่า any คือ อันใดอันหนึ่งก็ได้เลย - แต่ถ้า
not any()
หมายความว่า ถ้าไม่มีTrue
แม้แต่ตัวเดียวเลย ก้อจะทำนะ
if not any([student_registration_code, credit_bank_registration_code]):
raise ValidationError({'detail': 'Student code is required.'})
# ถ้าไม่มีค่าเข้ามาเลยทั้ง 2 ตัวแปรใน any() ก็จะทำใน raise นะ
3. ascii(object)
เป็นการ return string ออกมาปกติเลยในกรณีที่ใช้เป็นภาษาอังกฤษ จะไม่มีผลอะไรแตกต่าง แต่เมื่อใช้เป็นภาษาอื่นๆ(อักขระพิเศษ), ascii function จะ return ออกมาเป็น String ของ unicode ในภาษานั้นๆ เช่น
>>> ascii(1)
'1'
>>> ascii('hey')
"'hey'"
>>> ascii([])
'[]'
>>> ascii({})
'{}'>>> type(ascii([]))
<class 'str'>>>> type(ascii({}))
<class 'str'>>>> type(ascii(1))
<class 'str'>>>> type(ascii('encode'))
<class 'str'>>>> ascii('รักเธอ')
"'\\u0e23\\u0e31\\u0e01\\u0e40\\u0e18\\u0e2d'"
4. ord(c) : ใส่ argument ได้แค่ character ตัวเดียวเท่านั้นนะ
เป็นการแปลง character (ASCII) ตัวเดียวให้เป็น integer (Decimal) เพราะคอมพิวเตอร์จะรู้จักแค่ตัวเลข binary เท่านั้น ฉะนั้นการที่เราพิมพ์อะไรลงไป ทุกอย่างจะถูกแทนด้วยตัวเลข เช่น
>>> ord("a")
97
>>> ord("A")
65
>>> ord("B")
66
ตัว “a” ที่เราพิมพ์เข้าไปจะถูกแทนที่ด้วย 97 และ “A” ,”B” คือ 65 และ 66 ตามลำดับ
จริงๆแล้วเรายังสามารถนำมาประยุกต์ใช้กรณีที่ต้องการแปลงตัวอักษา A-Z
ให้เป็น 1–26
ก็สามารถทำได้ในลักษณะนี้
# ปกติ A=65 นะ เราจะนำมาลบ 64 จะเริ่มต้นที่ค่า 1 (ทีนี้เราจะได้ A-Z ที่ได้ 1-26 โดยไม่ต้องเขียนยาวๆเลยนะ)
# จาก student_code ที่มี Z อยู่ภายใน, function จะแปลงให้เป็น 26 เองเลย
student_code = '59Z10053211'
def convert_student_code_alphabet_to_number(student_code: str):
result = []
for code in student_code:
if code.isdigit():
result.append(int(code))
else:
result.append(ord(code.upper()) - 64)
return result
print(convert_student_code_alphabet_to_number(student_code=student_code))
# output
# [5, 9, 26, 1, 0, 0, 5, 3, 2, 1, 1] # z คือ 26 นะ
5. chr(i)
เป็นการแปลงค่าย้อนกลับหรือ เป็น inverse of ord หรือ คือการเแปลง interger (Decimal) ให้เป็น character (ASCII)เช่น
>>> chr(97)
'a'
>>> chr(65)
'A'
>>> chr(66)
'B'
6. bin(x)
เป็นการ return ค่า Binary ของ integer ที่รับเข้ามา โดยผลลัพธ์จะนำหน้าด้วย ob เช่น
>>> bin(36)
'0b100100'
>>> ิิ
>>> bin(11)
'0b1011'
>>> bin(-4)
'-0b100'
7. class bool([x])
เป็นการ return ค่า boolean ของ specified object ด้านใน เช่น
False
>>> bool(1 ==1)
True
>>> myAge = 27
>>> brotherAger = 25
>>> bool(myAge < brotherAger)
False
8. breakpoint(*args, **kws)
เป็นการ set breakpoint การใช้งานจะเหมือนกับการใช้ pdb แบบเดิมๆคับ
ซึ่งในการใช้งานเราเพียงแค่เพิ่ม breakpoint() ในจุดที่ต้องการ เช่น
for i in range(10):
print('i = ', i)
if i == 5:
breakpoint()
เมื่อ i = 5 จะเรียกใช้งาน pdb (แทนการเรียกใช้แบบรูปด้านบน)
9. class bytes([source[, encoding[, errors]]])
เป็น class ของ bytes ที่จะ return a bytes object มาให้เรา โดยสามารถระบุ encoding ได้ด้วย
>>> bytes()
b''>>> bytes("hey", "UTF-8")
b'hey'>>> bytes("hey", "UTF-16")
b'\xff\xfeh\x00e\x00y\x00'>>> bytes("hey", "UTF-32")
b'\xff\xfe\x00\x00h\x00\x00\x00e\x00\x00\x00y\x00\x00\x00'>>> bytes(1)
b'\x00'>>> bytes(4)
b'\x00\x00\x00\x00'>>> bytes([1,2,3])
b'\x01\x02\x03'
10. class bytearray([source[, encoding[, errors]]])
สำหรับ bytearray() จะเป็น function ที่ return a bytearray object คล้ายกับ bytes() เพียงแค่เป็น type bytearray() เท่านั้น
>>> bytearray()
bytearray(b'')>>> x = bytearray(4)
>>> x
bytearray(b'\x00\x00\x00\x00')
11. callable(object)
เป็นการตรวจสอบว่าเป็น object ไหม ถ้าใช่ก้อจะ return เป็น True (เพราะ callable), แต่ถ้าไม่ใช่ก้อจะเป็น False
>>> callable("Hey")
False # ใส่ String เข้ามามันไม่ได้ไง ไม่ callable
>>> callable(type("Hey"))
True
>>> type("Hey")
<class 'str'>
12. @classmethod
เป็นการ Converts a method into a class method หรือ การทำให้ function เป็นเหมือน class หนึ่ง (เพื่อให้เราสามารถสร้าง constructor ได้หลายๆแบบ ให้มากกว่า constructor ที่ผ่านตัว __init__แค่อย่างเดียวเท่านั้น)
class Eyeglasses:
def __init__(self, eye, bridge, temple):
self.eye = eye
self.bridge = bridge
self.temple = temple
@classmethod
def of(cls, frame_string):
s = frame_string.split('-')
return cls(int(s[0]), int(s[1]), int(s[2]))
@staticmethod
def gram_oz(g):
return g * 0.03
def __str__(self):
return "{}-{}-{}".format(self.eye, self.bridge, self.temple)
if __name__ == '__main__':
f1 = Eyeglasses(55, 16, 140)
f2 = Eyeglasses.of("55-16-140")
print(f1)
print(f2)
print(Eyeglasses.gram_oz(10))# -----------------------------------# Output:# 21
# 25
# True
13. compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
เป็น function ที่ return the specified source as a code object, ready to be executed.
x = compile('print(122)', 'love', 'eval')
print(x)
exec(x)# Output:
# 122
14. class complex([real[, imag]])
เป็น class ที่ return a complex number (จำนวนเชิงซ้อน) เช่น
x = complex(3, 5)
print(x)# (3+5j)
15. delattr(object, name)
ย่อมาจาก (delete atrribute) เป็น function ที่ช่วย deletes attribute จาก class ได้เลยนะ เช่น
class Person:
name = "Atthana"
age = 37
country = "Thailand"
person = Person()
print(person.age) # 37
print('----------')
delattr(Person, 'age') # Person จะไม่มี "age" property อีกต่อไปล่ะนะ
print(person.age) # บรรทัดนี้จะ error เพราะไม่มี age แล้ว
16. class dict
(**kwarg)
class dict
(mapping, **kwarg)
class dict
(iterable, **kwarg)
เป็น class ที่จะ return dictionary ออกมาโดยรับอะไรเข้าไปก็ได้ เป็น keyword arguments เช่น
x = dict(name = "Atthana", age = 37, country = "Thailand")
print(x)
print(x['name'])# output:
# {'name': 'Atthana', 'age': 37, 'country': 'Thailand'}
# Atthana
17. dir([object])
เป็น function ที่จะ return lists ของ properties ทั้งหมด และ methods ของ objects นั้นๆออกมาให้เห็น โดยที่ไม่มี values ออกมานะ เช่น
class Person:
name = "Q"
age = 36
country = "Thailand"
print(dir(Person))# output:
# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'country', 'name']
18. divmod(a, b)
เป็น function ที่ return ผลหาร เป็น tuple ของผลหารและเศษ เช่น
x = divmod(10, 5)
print(x)# output:
# (2, 0)
19. enumerate(iterable, start=0)
อ่านว่า (อะนิวมะเรท) แปลว่า แจกแจงนะคับ คือ ใช้ในการแจกแจงค่า index และข้อมูลใน index ในรูปแบบ Tuple ดังนี้ (Index, Value) โดยต้องใช้กับข้อมูลชนิด list โดยมี syntax คือ
enumerate(iterable, start)
x = ('apple', 'banana', 'cherry')
y = enumerate(x)print(list(y))# จะได้ [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
x เป็น tuple เก็บ String ไว้ 3 ค่า เมื่อทำการแจกแจงออกมาแล้วเก็บค่าไว้ที่ตัวแปร y และนำมาเก็บใน list จึงได้ [(0, ‘apple’), (1, ‘banana’), (2, ‘cherry’)] นั่นเอง
20. eval(expression[, globals[, locals]])
eval คือ evaluates เป็น function ที่จะทำการเช็คตัว expression ถ้าถูกต้องตามรูปแบบ Python ก้อจะทำการ execute ให้เลย มี syntax คือ
eval(expression, globals, locals)
x = 'print(55)'
y = 'abs(-35)'
eval(x)
print(eval(y))# output:
# 55
# 35
21. exec(object[, globals[, locals]])
เป็น function ที่จะ execute code ที่เราได้ระบุไว้ เช่น
x = 'name = "Q"\nprint(name)'
exec(x)
number = '123'
a = 'print(number)'
exec(a)# output:
# Q
# number
22. filter(function, iterable)
เป็นการกรองค่าออกมาจาก iterable object เช่น ในตัวอย่างด้านล่าง จะทำการ print(x) เมื่อ ages มีค่ามากกว่าหรือเท่ากับ 18 เท่านั้น เพราะ return เป็น True
ages = [5, 12, 17, 18, 24, 32]
def myFunc(x):
if x < 18:
return False
else:
return True
adults = filter(myFunc, ages)
for x in adults:
print(x)# output:
# 18
# 24
# 32
23. class float([x])
อันนี้น่าจะใช้กันบ่อย คือ แปลงค่าให้เป็น float นั่นเอง
x = float(3)
print(x) # 3.0
24. format(value[, format_spec])
อันนี้ใช้ในการ format a specified value into a specified format เช่น
x = format(0.5, '%')
y = format(255, 'x')print(x) # 50.000000%
print(y) # ff
ที่จะใช้อีกที่หนึ่งก้อคือตอนสั่ง print แล้วใช้ .format() ร่วมด้วย เช่น
name = "Atthana"
print("I am {}".format(name)) # I am Atthana
25. map
(function, iterable, ...)
เป็นการ map ให้ได้ค่าใหม่ที่เราต้องการ โดยจะใส่ iterable กี่ชุดก้อได้
def myfunc(a, b):
return a + bx = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))print(x)#convert the map into a list, for readability:
print(list(x))# output:
# <map object at 0x2add69f837b8>
# ['appleorange', 'bananalemon', 'cherrypineapple']
อีก used case
นะคับ สมมติว่าเราต้องการแยก String
แบบไม่มี space
ออกมา เราจะใช้ split()
ไม่ได้นะ ลองใช้ map
แทนก็น่าสนใจ
โดยใส่ function
เข้าไปจะเป็น str
, int
ก็ได้ และตามด้วย iterable
นั่นคือ number
number = '1234'
list(map(str, number)) # ['1', '2', '3', '4']
list(map(int, number)) # [1, 2, 3, 4]
26. open(file, mode)
เป็น function สำหรับเปิดไฟล์ และ return ออกมาเป็น file object.
f = open("demofile.txt", "r")
print(f.read())# output:
# Hello! Welcome to demofile.txt
# This file is for testing purposes.
# Good Luck!
27. next(iterable, default)
เป็น function ที่จะ return next item ใน iterator (iter) ออกมานะ ฉะนั้นะถ้าจะใช้กับ for loop ก็ต้องทำให้เป็น iterator โดยการครอบด้วย iter() หรือ เช่น
# List ที่เป็น iterable
numbers = [1, 2, 3, 4]
# สร้าง iterator object จาก list
iterator = iter(numbers)
# ดึงค่าทีละตัวด้วย next()
print(next(iterator)) # Output: 1
print(next(iterator)) # Output: 2
print(next(iterator)) # Output: 3
print(next(iterator)) # Output: 4
# ถ้าดึงต่อจะเกิด StopIteration
# print(next(iterator)) # Error: StopIteration
แต่ถ้าข้อมูลเราเป็น list ธรรมดา จะใช้ next() ไม่ได้
ต้องแปลงเป็น iterable ด้วยฟังก์ชัน iter() ในลักษณะนี้
my_list = ["one", "two", "three"] # แบบนี้จะใช้ next()ไม่ได้
แบบนี้ใช้ไม่ได้ ต้องแปลงด้วยฟังก์ชัน iter()
my_list = iter(["one", "two", "three"])
จากนั้นก็ใช้งาน next() ได้ล่ะ
my_list = iter(["one", "two", "three"])a = next(iter(my_list))
print(a)
a = next(iter(my_list))
print(a)
a = next(iter(my_list))
print(a)
# ----- output -----
one
two
three
Iterables คือการทำอะไรซ้ำๆ โดยปกติจะทำกับ List หรือ Array
เนื้อหา iterable สามารถอ่านได้สน link คับ
Used case ของ next()
ที่ผมคิดว่ามีประโยชน์นะคับคือ
28. reversed(sequence)
อันนี้ตรงๆตัวเลยคับ คือ ช่ย reverse และ return ออกมาเป็น object ฉะนั้นจึงต้องใช้ loop for ช่วยถ้าต้องการดูค่าภายใน
mylist = ['apple', 'banana', 'mango']
newFruit = []
print(mylist)
new_mylist = reversed(mylist)
for i in new_mylist:
newFruit.append(i)
print(newFruit)# output:
# ['apple', 'banana', 'mango']
# ['mango', 'banana', 'apple']
29. vars(object)
เป็น function ที่ returns the __dic__ attribute of an object
__dict__ attribute คือ dictionary ที่เก็บ object ของ attribute ที่สามารถเปลี่ยนแปลงได้
class Person:
name = "John"
age = 36
country = "norway"x = vars(Person)print(x)# output:
# {'__module__': '__main__', 'name': 'John', 'age': 36, 'country': 'Norway', '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
30. zip(iterator1, iterator2, iterator3 …)
เป็น function ที่ return a zip object คือ ช่วยให้เรารวมข้อมูลใน list ตำแหน่งเดียวกัน ให้จับคู่กันได้ ไม่ว่าจะให้ออกมาเป็น tuple
, list
หรือ dict
ก็ได้ อยู่ที่เราจะกำหนดให้กับ iterables
name = ["John", "Charles", "Mike"]
age = [35, 23, 16]
student = zip(name, age)
print(dict(student))
# print(list(x))# output:
# {'John': 35, 'Charles': 23, 'Mike': 16}
อาจจะมองไม่เห็นภาพใช่ไหมครับ ว่า used case จริงๆ จะใช้ในกรณีไหน นี่เลย
def calculate_check_digit(student_code: str, ref2: str, amounts: str) -> str:
weight_list = [7, 5, 1] * 10
weight_r1 = weight_list[:11] # First 11 digits for ref1
weight_r2 = weight_list[11:21] # Since position 12-21 for ref2
weight_amount = weight_list[21:] # Since 22 onwards for amount
r1_list = [int(r1) for r1 in student_code]
r2_list = [int(r2) for r2 in ref2]
amount_list = [int(amount) for amount in amounts]
sum1 = sum(w * d for w, d in zip(weight_r1, r1_list))
sum2 = sum(w * d for w, d in zip(weight_r2, r2_list))
sum3 = sum(w * d for w, d in zip(weight_amount, amount_list))
check_digit = str((sum([sum1, sum2, sum3]) * 2) % 100)
return check_digit.zfill(2) if len(check_digit) < 2 else check_digit
check_digit = calculate_check_digit(
student_code='55050427733',
ref2='1234567890',
amounts='15000'
)
print(check_digit)
# output
# 80
31. print(*objects, sep=' ', end='n', file=sys.stdout, flush=False)
>>> print("Hello world")
Hello world
>>>
print() นี่คือง่ายๆเลยนะคับ วิธีการใช้เพิ่มเติมดูจากที่เขียนไว้ ที่นี่ นะคับ
32. min(arg1, arg2, *args[,key])
โดย function นี้จะคำนวณค่าที่น้อยที่สุดระหว่าง arg1 และ arg2 และ return ค่าที่น้อยที่สุดที่คำนวณได้ออกมา (แต่ arguments ทั้งหมดต้องเป็นข้อมูลชนิดเดียวกันนะคับ)
>>> min(500, 300,-199, 0, 200, 100, -54)
-199
จะ return ค่า -199 ที่น้อยที่สุดออกมา
33. max(arg1, arg2, *args[, key])
อันนี้จะตรงข้ามกับ min() นะคับ แค่เปลี่ยนจากหาค่าน้อยที่สุดเป็น หาค่ามากที่สุดแทน
>>> max(500, 300,-199, 0, 200, 100, -54)
500
- เราสามารถกำหนดวิธีการหาค่า max ใน argument ต่างๆด้วย keys ได้ด้วยนะ
- จาก code ด้านล่างจะเห็นว่า max() จะได้ค่า obj ของ TaxData ที่มีค่า id มากที่สุดนะ เพราะใน key เป็นการแจกแจง id ออกมา
- จากนั้นใช้
.id
เพื่อให้ได้latest_record_id
นั่นเอง
records = [<TaxData: 08000183>, TaxData: 08000183>]
max(records, key=lambda x: x.id) # records คือ iterable ที่จะมาหา max และกำหนดวิธีการหาด้วย function ใน keys นะ
latest_record_id = max(records, key=lambda x: x.id).id # เราจะเลือกอันนี้นะ id max
34. abs(x)
Function นี้คือ absolute (ค่าสัมบูรณ์) โดยจะทำให้ค่าที่ return ออกมาเป็นเลขจำนวนเต็มบวกเท่านั้น
>>> value = -45
>>> abs(value)
45
35. round(number[, ndigits])
จะเป็นการปัดเลขให้เป็นจำนวนเต็มแบบวิทยาศาสตร์เลย คือ ถ้าค่ามากกว่า 0.5 ก็จะปัดให้เป็นจำนวนเต็มเลย เช่น 2.6 ก้อจะปัดให้เป็น 3 ,ส่วน 2.5 ก็ยังเป็น 2 อยู่เป็นต้น
>>> round(24.4)
24
>>> round(24.5)
24
>>> round(24.6)
25
>>> round(24.51)
25
>>> round(24.54)
25
>>> round(24.55)
25
36. pow(base, exp[, mod])
เป็น function ในการคำนวณเลขยกกำลัง โดย base = ฐานที่ใช้ในการยกกำลัง และ exp (exponential) = เลขชี้กำลัง และจะ return ค่าเป็นผลลัพธ์จากการยกกำลังออกมานั่นเอง เช่น
>>> pow(9, 2)
81
>>> pow(3, 4)
81
>>> pow(4,2)
16
37. hasattr(object, name)
เป็น function ที่ใช้ในการตรวจสอบว่ามี attribute (property/ method) ที่เราระบุไว้ไหม โดยจะ return ออกมาเป็น True หรือ False เช่น
class Person:
name = 'Atthana'
age = 37
country = 'Thailand'
x = hasattr(Person, 'ages') # เช็คว่า object Person มี ages รึป่าวซึ่งไม่มี
print(x)
y = hasattr(Person, 'age') # เช็คว่า object Person มี age รึป่าวซึ่ง "มี"
print(y)# ---- output ----
False # เพราะ ages ไม่มีจึง return มาเป็น False
True # เพราะ age มีจึง return มาเป็น True
ถัดไปลองมาดูการประยุกต์ใช้ใน Django ดูนะคับ
38. set()
Set is a collection which is unordered and unindexed. No duplicate members.คือมีคุณสมบัติของ distinct = การแสดงข้อมูลที่ไม่ซ้ำกัน
สำหรับ set method เป็น 1 ใน 4 built-in data types (List, Tuple, Dict )ที่ใช้ในการเก็บ collections of data ซึ่งใช้ในการแปลงข้อมูลที่ซ้ำกัน ให้เหลือเพียงแค่ตัวเดียว (Duplicates not allowed)
set จะ collection ที่ unordered และ unindexed นะคับ คือ เราไม่สามารถจัดเรียงและระบุ index ก็ไม่ได้
สำหรับประโยชน์ของมันนะคับ คือ ใช้ในการกำจัด elements ที่ซ้ำกันออกไป และถ้าเราต้องการที่จะ index ได้ ก็เพียงแต่แปลงให้เป็น list อีกครั้ง เช่น
39. isinstance()
เป็นการเช็คว่าเป็น type หรือ class นั้นๆรึป่าว
ตัวอย่างนะ เป็นการเช็คว่า object นี้เป็นมาจาก class หรือ type นี้รึป่าว
จริงๆแล้ว เราสามารถรับเป็น list หรือ values อะไรก็ได้นะ ไม่จำเป็นต้องเป็น object ของ class เสมอไป เพราะใน Python ทุกอย่างคือ object หมดเลย
Used case:
คือ เราสามารถ apply เพื่อใช้เช็คตอนรับ boolean เข้ามา บางครั้งถ้าส่งเป็น string อาจทำให้ logic ผิดพลาดได้ จึงต้องดักเอาไว้ก่อน
สำหรับ painpoint
ของ isinstance
คือ มันเช็คได้แค่ generic type
ไง จะใช้ type
ที่เรา custo
ขึ้นมาเองไม่ได้ ถ้าเราต้องการให้ได้ ต้องทำแบบนี้นะ
- Ex3: นี้เป็นตัวอย่างของการให้เช็คว่าเป็น
list
ของdate
รึปาว
@staticmethod
def is_list_of_dates(obj):
if isinstance(obj, list):
for item in obj:
if not isinstance(item, datetime.date):
return False
return True
return False
วิธีใช้นะ
- เช็คว่า
**self.payment_periods**
เป็น**list**
ของ**date**
ป่าว ถ้าใช่ก็ค่อยไปดึงแต่ละ index ออกมา
if self.is_list_of_dates(self.payment_periods):
start_date = get_date_format_en_th(self.payment_periods[0], is_abbr=True).lstrip('0')
end_date = get_date_format_en_th(self.payment_periods[1], is_abbr=True).lstrip('0')
return f'{start_date} - {end_date}'
40. rstrip()
สำหรับเคสนี้มันคือ right strip
คือ จะตัวด้านขวาออก โดยระบุสิ่งที่ต้องการ remove
ด้านในได้เลย มาดู Used case
กันเลยดีกว่านะ