A Cheatsheet for Python Built-in Functions (Part 2: C-D)
# *** callable() ***
def func0():
pass
print(callable(func0)) # Output: True
# *** chr() ***
print(chr(65)) # Output: A
# *** classmethod() ***
# Note: The new @classmethod decorator should be used instead of
# the built-in function classmethod().
class MyClass1:
myProperty = 1234
def myFunc(self):
print(self.myProperty)
obj0 = MyClass1()
obj0.myFunc()
MyClass1.myFunc = classmethod(MyClass1.myFunc)
MyClass1.myFunc() # myFunc is used as a class method (vs. instance method)
# *** compile() ***
myCode = '_a = 10 \n_b = 20 \nmySum = _a + _b \nprint("mySum =", mySum)'
myCodeObject = compile(myCode, 'myCodeString', 'exec')
exec(myCodeObject) # Output: 30
# *** complex() ***
print(complex(1, 2)) # Output: (1+2j)
# *** delattr() ***
class MyClass2:
myProperty1 = 1234
myProperty2 = 'ABC'
myObj2 = MyClass2()
print(myObj2.myProperty2)
delattr(MyClass2, 'myProperty2')
#print(myObj2.myProperty2) # Error: AttributeError: 'MyClass2' object has no attribute 'myProperty2'
# *** dict() ***
myDic1 = dict(key1 = "val1", key2 = "val2", key3 = "val3")
print(myDic1) # Output: {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
# *** dir() ***
class MyClass3:
myProperty1 = 1234
def myMethod1():
pass
print(dir(MyClass3)) # 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__', 'myMethod1', 'myProperty1']
"""
# *** divmod() ***
print(divmod(7, 3)) # Output: (2, 1)
# Note: The output is a tuple:
# divmod(dividend, divisor) => (quotient, reminder)
No comments:
Post a Comment