OneCoder


  • 首页

  • 归档

  • 标签

  • 关于

  • 搜索

Python练习-type 和 metaClass

发表于 2022-08-10

本部分学习用Type和metaClass动态创建类,添加属性和方法。

# 使用元类 type 可以检查对象类型,也可以动态创建一个新类

class Student(object):
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender

    def do_study(self, value):
        print(self.name, "is studying", value)


stu2 = Student("S-Name", 18)
print(type(stu2))


def fn(self, name):
    print("Hello:", name)


MetaStu = type("MetaStu", (object,), dict(hello=fn))
meta_stu_instance = MetaStu()
meta_stu_instance.hello("Coder")


# 使用metaclass类
# 先定义metaclass,就可以创建类,最后创建实例。
# 所以,metaclass允许你创建类或者修改类。换句话说,你可以把类看成是metaclass创建出来的“实例”。

# 可以通过__new__方法动态添加属性和方法
class StudentMetaClass(type):
    def __new__(cls, name, bases, attrs):
        attrs['study'] = lambda self, value: self.do_study(value)
        return type.__new__(cls, name, bases, attrs)


class MyStudent(Student, metaclass=StudentMetaClass):
    pass


my_stu = MyStudent("OneCoder", 38)
my_stu.study("Python")

输出如下:

阅读全文 »

Python练习-定制类和枚举

发表于 2022-08-08

本部分学习Python中定制类和枚举部分。定制类其实就是类似Java中复写String,HashCode等方法,不过更灵活,可覆盖的方法更多。

阅读全文 »

Python练习-高级面向对象

发表于 2022-08-07

本部分练习Python高级面向对象内容,主要学习__slots__和@property相关用法,详见代码:

阅读全文 »

Python练习-面像对象基础

发表于 2022-08-04

本部分练习Python面像对象编程基础知识。练习代码如下:

阅读全文 »

Python练习-模块和初级面像对象

发表于 2022-08-01

本部分练习Python模块和初级面像对象相关知识。练习代码如下:

阅读全文 »

python练习-函数式编程(二)

发表于 2022-07-19

本部门练习Python函数式编程,第二部分。

阅读全文 »

python练习-函数式编程(一)

发表于 2022-06-20

本部分练习Python函数式编程。练习高阶函数、map、reduce等常用函数。

阅读全文 »

python练习-高级特性

发表于 2022-06-07
# 高级特性
# 1. 切片和列表生成器
from collections.abc import Iterable, Iterator

list_one = list(range(10))
print(list_one[:3])
print(list_one[2:7])
print(list_one[-5:-1])
# 取后5个数
print(list_one[-5:])
# 取偶数
print(list_one[:10:2])
# 取奇数
print(list_one[1:10:2])
# 字符串也可以切片
str_one = "My name is Yummy"
print(str_one[:5])
print(str_one[:10:3])


def trim_str(str):
    result = str
    if str[-1] == " ":
        result = str[:-1]
    return result


print(trim_str("Yummy ") + "!")
print(trim_str("Yummy") + "!")

# 2. 迭代
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
    print(key)
for v in d.values():
    print(v)
for k, v in d.items():
    print(k, v)
for s in "Yummy":
    print(s)

print(isinstance(123, Iterable))

for i, value in enumerate(["A", "B", "C"]):
    print(i, value)

for x, y in [(1, 2), (4, 6), (7, "A")]:
    print(x, y)


# 测试
def findMinAndMax(param):
    max, min = None, None
    if param and param != []:
        for v in param:
            if max == None:
                max = min = v
            elif v > max:
                max = v
            elif v < min:
                min = v
    return (min, max)


if findMinAndMax([]) != (None, None):
    print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
    print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
    print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
    print('测试失败!')
else:
    print('测试成功!')

# 3. 列表生成
list_two = [x * x for x in range(1, 11)]
print(list_two)
list_three = [x * x for x in range(1, 11) if x % 2 != 0]
print(list_three)
list_four = [m + n for m in "ABC" for n in "123"]
print(list_four)
d_str = {"A": "1", "B": "2", "C": "3"}
list_five = [k + "=" + v for k, v in d_str.items()]
print(list_five)
# 变成小写
print([v.lower() for v in list_five])
list_six = [x * x if x % 2 == 0 else -x for x in range(1, 11)]
print(list_six)
# 练习变小写,需要判断类型
L1 = ['Hello', 'World', 18, 'Apple', None]
L_output = [x.lower() if isinstance(x, str) else x for x in L1]
print(L_output)

# 4. 生成器
g = (x * x if x % 2 == 0 else -x for x in range(1, 11))
next(g)
print(next(g))
for v in g:
    print(v)


def feb(max):
    a, b, n = 0, 1, 0
    while n < max:
        a, b = b, a + b
        yield a
        n += 1
    return "over"


fg = feb(10)
for v in fg:
    print(v)


# 练习:生成器,杨辉三角形
#           1
#          / \
#         1   1
#        / \ / \
#       1   2   1
#      / \ / \ / \
#     1   3   3   1
#    / \ / \ / \ / \
#   1   4   6   4   1
#  / \ / \ / \ / \ / \
# 1   5   10  10  5   1
def g_triangle():
    last_row = [1]
    cur_row = [1]
    n = 0
    while n < 10:
        if n == 0:
            cur_row = [1]
        elif n == 1:
            cur_row = [1, 1]
        else:
            idx = 1
            while idx < n:
                cur_row.append(last_row[idx - 1] + last_row[idx])
                idx += 1
            cur_row.append(1)
        yield cur_row
        last_row = cur_row
        cur_row = [1]
        n += 1
    return


n = 0
results = []
for t in g_triangle():
    results.append(t)
    n = n + 1
    if n == 10:
        break

for t in results:
    print(t)

if results == [
    [1],
    [1, 1],
    [1, 2, 1],
    [1, 3, 3, 1],
    [1, 4, 6, 4, 1],
    [1, 5, 10, 10, 5, 1],
    [1, 6, 15, 20, 15, 6, 1],
    [1, 7, 21, 35, 35, 21, 7, 1],
    [1, 8, 28, 56, 70, 56, 28, 8, 1],
    [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
]:
    print('测试通过!')
else:
    print('测试失败!')

#5. 迭代器 可以被next()函数调用并不断返回下一个值的对象称为迭代器
print(isinstance((x for x in range(10)), Iterator))
print(isinstance((x for x in range(10)), Iterable))
print(isinstance([], Iterator))
print(isinstance([], Iterable))
阅读全文 »

python练习-Hello World

发表于 2022-05-19
# Python demo for lihz
# 1. Hello World
print("Hello World Python")

# 2. 输入输出
print("The quick brown fox", "jumps over the lazy dog")
print("100", "+", "200", "=", 100 + 200)
# name = input("What is your name ? \r\n")
# print("My name is",name)
print('''Line1
Line2
Line3''')

# 3. 字符串
print(chr(66))
print(chr(22334))
# bytes 数据类型
x = b'abc'
print(x)
print("中文".encode("utf-8"))
print(b'\xe4\xb8\xad\xe6\x96\x87'.decode("utf-8"))
print("My name is %s" % "OneCoder")
age = 38
print(f"My age is {age}")

# 4. list  tuple
# list 有序集合
numbers = ["8676", "8616", "8385"]
print("The length of list numbers is %s" % len(numbers))
numbers.append("8528")
numbers.pop(1)
numbers.insert(1, "8448")
print(numbers)

# tuple 不可变元组
families = ("Dad", "Mum", "Son")
print(len(families))
one = (1,)
print(one)
print((1))

# 5. 判断和循环
number = 20
if int(number) > 18:
    print(number)
elif int(number) > 6:
    print("less than 18")

sum = 0
for x in range(101):
    sum += x
print(sum)

# 6. dict即map和Set
d = {"Dad": 38, "Mum": 37}
print(d["Mum"])
print(d.get("Son", "Yummy"))
# set 元素不重复
s1 = set([1, 2, 3, 3])
print(s1)
s2 = set([2, 3, 4])
s1.add(5)
print(s1 & s2)
print(s1 | s2)

# 7. 函数
h = hex
print(h(12))


def print_name(name):
    print("My name is", name)


def return_tuple():
    return 12, 34


x, y = return_tuple()
print(x)
print(y)
print_name("Yummy")


def power(x, n=2):
    s = 1
    while n > 0:
        s = s * x
        n -= 1
    return s


print(power(5))
print(power(5, 3))


def sums(*nums):
    result = 0
    for i in nums:
        result += i
    return result


print(sums(1, 2, 3, 4, 5))


def person(name, age, **others):
    print("Name:", name, "Age:", age, "Others: ", others)


extra = {"city": "DaLian", "gender": "Male"}
# 获得的室extra的拷贝,修改不会影响extra的值
person("Yummy", 8, **extra)


def person_two(name, age, *, city):
    print("Name:", name, "Age:", age, "City:", city)


person_two("Yummy", 8, city="DaLian")


def f1(a, b, c=1, *args, **kwargs):
    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kwargs)


f1(1, 2, 4, 4, 4, 4, kwargs={"5": 5})
阅读全文 »

2021-11-16 - 无题

发表于 2021-11-16

人,

应该活得优秀被别人赞扬,

还是应该精致利己,满足私欲。

阅读全文 »
1 2 3 4 … 36
LiHongZhe

LiHongZhe

onecoder's blog.

352 日志
8 分类
RSS
Creative Commons
Links
  • 酷壳
  • 煮酒品茶
  • 小弟子的网络之路
  • 图表秀-在线图表制作
© 2012 - 2022 LiHongZhe
由 Jekyll 强力驱动
主题 - NexT.Muse
本站访客数 人次 本站总访问量 次