__getnewargs
__hash
__init
__init_subclass
__iter
__next
strA = 'abcdefg hijklmn'
# 集合对象序列化
# 并转换为 n+1 元数组
print(strA.__getnewargs__()[0])
tup = (1, 2, 3, 4)
print(tup.__getnewargs__())
# 打印哈希值
# hash值是一直变化的,不是固定的
# 每次运行程序得到的结果都不同
print(strA.__hash__())
a = 'a'
print(a.__hash__())
# 相关参数初始化
# 需要哪些属性及属性值可以在__init__中定义
print(strA.__init__())
# 一般用在类的属性方法
# __init_subclass__
# 可以代替元类进行变量属性的填充
# 如果使用该方法则不需要提前定义任何属性
# 或者说一时间想不到的属性
class testInit:
def __init__(self):
self.a = 3
self.b = 4
def __init_subclass__(cls, **kwargs):
for k, v in kwargs.items():
type.__setattr__(cls, k, v)
def say(self):
print('Hello I am {0}'.format(self.name))
# 创建一个类并继承testInit类
# 在参数中填写需要的属性和属性值
# 相当于创建testInit对象了
#
class testSub(testInit, name='Edith', age=19, position='ShangHai'):
def __init__(self):
super().__init__()
tinit = testInit()
print(tinit.a)
print(testSub.name, testSub.position, testSub.age)
testSub.say(testSub())
ts = testSub()
print(ts.a)
class TestIter:
def __init__(self):
self.a, self.b = 0, 1
def __iter__(self):
return self
# next 与 指针类似
# 自动根据条件执行程序并记录
# 所有的内置方法都要进行重写才有灵魂
def __next__(self):
self.a, self.b = self.b, self.a + self.b
print("1:", self.a, self.b)
if self.a > 1000:
# 3.8版本Python raise有问题,
# 运行多次都不会报错(错误)
# 偶尔一次报错(正确)
# raise StopIteration()
print("Fail")
return self.a, self.b
iter1 = TestIter()
while iter1.a < 1000:
print('2 iter1.__next__()', iter1.__next__())
结果
abcdefg hijklmn
((1, 2, 3, 4),)
4608941156233210214
7464789024282092041
None
3
Edith ShangHai 19
Hello I am Edith
3
1: 1 1
2 iter1.__next__() (1, 1)
1: 1 2
2 iter1.__next__() (1, 2)
1: 2 3
2 iter1.__next__() (2, 3)
1: 3 5
2 iter1.__next__() (3, 5)
1: 5 8
2 iter1.__next__() (5, 8)
1: 8 13
2 iter1.__next__() (8, 13)
1: 13 21
2 iter1.__next__() (13, 21)
1: 21 34
2 iter1.__next__() (21, 34)
1: 34 55
2 iter1.__next__() (34, 55)
1: 55 89
2 iter1.__next__() (55, 89)
1: 89 144
2 iter1.__next__() (89, 144)
1: 144 233
2 iter1.__next__() (144, 233)
1: 233 377
2 iter1.__next__() (233, 377)
1: 377 610
2 iter1.__next__() (377, 610)
1: 610 987
2 iter1.__next__() (610, 987)
1: 987 1597
2 iter1.__next__() (987, 1597)
1: 1597 2584
Fail
2 iter1.__next__() (1597, 2584)
15
15
4
20
Process finished with exit code 0
__len
__mod
__mul
# 前后两个方法相同
# 即计算长度
# len == length
print(strA.__len__())
print(len('abcdefg hijklmn'))
# 对象与对象取模
c = 4
d = 5
print(c.__mod__(d))
# 对象与对象取乘法
print(c.__mul__(d))
结果
15
15
4
20
转发评论收藏加关注呦
转发评论收藏加关注呦
转发评论收藏加关注呦
转发评论收藏加关注呦
转发评论收藏加关注呦