python_基本語法學習_1


# 十進制 --》 二進制
bin(10)
# 8進制
oct(10)
#十六進制
hex(10)

dic = {}
dic = {'a': 1, 'b': 2}

dic = dict(zip(['a', 'b'], [1,2]))
dic = dict([('a',1),('b',2)])
# Out:  {'a': 1, 'b': 1}

# 切片    range(start, stop, step)
a = [1,4,2,3,1]
my_slice = slice(0,5,2) # 1,2,1
# tuple 將對象轉爲一個不可變的序列類型
a = [1,3,5]
t = tuple(a)

# 四捨五入
a = round(10.045, 2)

# 返回對象內存大小
import sys
a = {'a':1, 'b':2.0}
big = sys.getsizeof(a)

# 排序
a = [ {'name':'xiaoming', 'age':38, 'gender':'male'},
      {'name':'xiaohong','age':20, 'gender':'female'} ]

sorted(a, key=lambda x: x['age'], reverse=False)
# 如果可迭代對象的所有元素都爲真,那麼返回 True,否則返回False
all([1,0,3,6])      # False
all([1,2,3])        # True

#接受一個可迭代對象,如果可迭代對象裏至少有一個元素爲真,那麼返回True,否則返回False
any([0,0,0,[]])     # False
any([0,0,1])        # True
# 獲取用戶輸入內容
input()
print()

print("i am {0},age {1}".format("tom",18))
print("{:+.2f}".format(-1)) # 帶符號保留小數點後兩位
print("{:.2%}".format(0.718)) # 百分比格式
print("{:.2e}".format(10241024)) # 指數記法

class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

# 使用@property裝飾器,實現與上完全一樣的效果:
class C:
    def __init__(self):
        self._x = None
    @property
    def x(self):
        return self._x
    @x.setter
    def x(self, value):
        self._x = value
    @x.deleter
    def x(self):
        del self._x

c = C()
c._x = 1
c.setx(2)

class Student():
    def __init__(self, id,name):
        self.id = id
        self.name = name
    def __call__ (self):
        print('I am {} , id = {}'.format(self.name, self.id) )


xm = Student(1, 'xiaoming')
xh = Student(id=2, name='xiaohong')

# 是否可以調用
# 判斷對象是否可被調用,能被調用的對象是一個callable 對象
callable(xm)
# 如果 xm能被調用 , 需要重寫Student類的__call__方法:
xm()        # I am xiaoming

# 動態刪除屬性,   刪除對象屬性, hash 獲取對象hash
delattr(xm,'id')
hasattr(xm, 'name')    # True
hash(xm.id) # 'Student' object has no attribute 'id'

# 動態獲取對象屬性
getattr(xm, 'name')
# 判斷對象是否有這個屬性
hasattr(xm, 'id')

# 判斷object是否爲classinfo的實例,是返回true
isinstance(xm, Student)

class Undergraduate(Student):
    pass

# 判斷 Undergraduate 類是否爲 Student 的子類
issubclass(Undergraduate, Student)

"""
一鍵查看對象所有方法
不帶參數時返回當前範圍內的變量、方法和定義的類型列表;
帶參數時返回參數的屬性,方法列表。
"""
dir(xm)
"""
['__call__',
 '__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__',
 'name']
"""

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章