类的属性和方法
#coding=utf-8
class Vector(object):
def __init__(self,a,b):
self.a=a
self.b=b
def __str__(self):
return "Vector(%d,%d)" %(self.a,self.b)
def __add__(self,other):
return Vector(self.a+other.a,self.b+other.b)
def __del__(self):
print('Vectory is deleted')
def __repr__(self):
return("repr--------")
def __call__(self):
return self.a
x=Vector(1,3)
y=Vector(5,2)
print(str(x))
print(x)
print(x+y)
print(repr(x))
print(x.__module__)
print(x.__class__)
del(x)
1.__add__方法
使用x+y
2.__str__方法
str(x)或x 直接输出时是调用str方法
3.__del__方法
del(x) 程序执行结束后也会自动执行del方法
4.__repr__方法:
repr(x) 一般是在初始化或结束后用
5.__module__属性
Vector.__module 如果结果为main则说明是当前文件,如果为其他则说明是导入的
6.__class__属性
Vector.__class__ 结果:<class '__main__.Vector'>
7.__call__方法
p()调用call方法
#coding='utf-8'
class Person(object):
def __init__(self,name):
self.name=name
def __call__(self):
return self.name
p=Person('zwj')
print(p())
8.__dict__属性
类和对象分别有自己的方法和属性
###对象为列表形式#######
#coding=utf-8
class Foo(object):
def __init__(self,name,age):
self.name=name
self.age=age
self.li=[12,3,5,6]
def __getitem__(self,item):
#匹配对象[item]形式
#如果是切片slice对象
if isinstance(item,slice):
return self.li[item]
#返回切片结果
elif isinstance(item,int):
#如果是整数,则说明是索引
return self.li[item]
def __setitem__(self,key,value):
#匹配:对象[key]=value这种形式
self.li[key]=value
def __delitem__(self,key):
#匹配:del对象的[key]形式
print(key)
del self.li[key]
f=Foo('zwj',15)
print(f[1:3]) #获取getitem方法
f[1]=1 #获取setitem方法
print(f[1])
del f[1]
print(f[1])
9.__getitem__方法
f[2:4] 或f[3]
10.__setitem__方法
f[1]=10
11.__delitem__方法
del f[1]
###iter和next#####
#coding=utf-8
class MyNumbers:
def __iter__(self):
self.a=1
return self
def __next__(self):
x=self.a
self.a+=1
return x
m=iter(MyNumbers())
print(next(m))
print(next(m))
12.__iter__方法
m=iter(MyNumbers())
13.__next__方法
next(m)
14.__slots__属性 绑定属性用来限制输入的内容
#coding=utf-8
class Student:
__slots__=('name','age')
s=Student()
s.age=25 #绑定属性age
s.score=99 #绑定属性score 不能输出
15.__new__
#coding=utf-8
class A:
def __init__(self,age,name,info):
print("init")
print(age,name,info)
def __new__(cls,*args,**kwargs):
print("new %s" %cls)
return object.__new__(cls)
A("WW",12,info=100)
*arg 代表多个参数age,name
**kwargs 代表多info=100这种类型的参数
先调__new__,返回cls
浙公网安备 33010602011771号